In C++ a constructor is a function with the same name as the class. Its purpose is to
- Create a new instance of the class
- Initialize the member data of the instance
Default Constructors
If you have written a constructor for your class then when you create an instance of it, the constructor is automatically called. If you haven't supplied a constructor, then the compiler will create a default one for you. This default constructor takes no parameters, or has default values for all parameters. A default parameter is one where the parameter value is supplied in the definition. For example in the class aclassnameaclassname(int param=5) {The 5 is the default value parameter. It means that the constructor can be called as
value = param
}
aclassname fredand the value 5 is passed in, or 7 below
aclassname fred(7) // overrides the default 5Here's a longer example.
class phonerec {You can of course write your own default constructor. You only get a default constructor supplied for free if you haven't written any kind of constructor. If you create one with non defaulted parameters and the compiler needs a default constructor, it will generate an error. It also doesn't like multiple default constructors as it has no way to tell which to use.
public:
string name;
string phonenumber[16];
phonerec(string myname ="Me",string myphone="555-1000") ; // defaults
};
phonerec p; // calls the constructor a default parameter "Me"
phonerec p("David","0207 384") ;
On the next page : Initializing Default Constructors

