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:
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.
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