Constructors

A constructor is a function that is called to initialize an object when it is created. A constructor must be defined as follows:

Multiple constructors may be defined for different initialization situations. As with all overloaded functions, they must have different parameter lists so that the compiler can distinguish between calls to the different constructors. There are several different types of constructors:

default constructor
The default constructor has no parameters. It will be called whenever an object is created and not given an initial values. If you don't create any constructors, the compiler will give you a default constructor which is empty. If you create any other constructors you must write a default constructor too. Example: Date();
copy constructor
The copy constructor has an existing object of the same class as its parameter. The parameter must be passed by reference. It will be called whenever an object is initialized to be a copy of an existing object. This occurs when you declare an object and initialize it to be a copy, and it also occurs when the compiler creates a temporary copy of an object, such as when an object is passed by value and when an object is returned by a function. If you don't create a copy constructor the compiler will give you one that copies each data member of the parm into the object being initialized. Example: Date(const Date&);
initializing constructor
An initializing constructor has one or more parameters that are used to initialize data members. There can be multiple initializing constructors. Examples: Date(int,int,int); and Date(int);

Constructors are never called explicitly. They are called automatically whenever an object is created. The compiler will select which constructor to call based on the initialization values provided (if any) when the object is declared.

Examples

Given the following class definition, and client code functions that use Date objects:

class Date
{
public:
   Date();
   Date(int);
   Date(int,int,int);
   Date(const Date&);
   void setDate(int,int,int);
   void showDate();
   void showWithName();
   int sameDate(Date);
private:
   int month;
   int day;
   int year;
};

void firstfunc(Date);
void secondfunc(Date &);
Date thirdfunc();

The following shows which constructor will be called:

Statement Constructor Called Explanation
Date one; Date(); default
Date two(12); Date(int); initializing
Date three(2,16,2006); Date(int,int,int); initializing
Date four(two); Date(const Date&); copy
firstfunc(one); Date(const Date&); copy constructor called to initialize formal parm
secondfunc(two); none no Date object is created
three = thirdfunc(); Date(const Date&); copy constructor called to initialize temporary object created for the return value


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2006