Login    New User    Forgot Password    Help      

Constructor Part(II)


In C++ a constructor is a function with the same name as the class. Its purpose is to

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 aclassname
 aclassname(int param=5) {   value = param } 
The 5 is the default value parameter. It means that the constructor can be called as
 aclassname fred 
and the value 5 is passed in, or 7 below
 aclassname fred(7) // overrides the default 5 
Here's a longer example.
 class phonerec {     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") ; 

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.

Copy Constructors

copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment).

  • A variable is declared which is initialized from another object, eg,
    Person q("Mickey"); // constructor is used to build q.  Person r(p);        // copy constructor is used to build r.  Person p = q;       // copy constructor is used to initialize in declaration.  p = q;              // Assignment operator, no constructor or copy constructor.
  • A value parameter is initialized from its corresponding argument.
    f(p);               // copy constructor initializes formal value parameter.
  • An object is returned by a function.

C++ calls a copy constructor to make a copy of an object in each of the above cases. If there is no copy constructor defined for the class, C++ uses the default copy constructor which copies each field, ie, makes ashallow copy.

Difference between copy constructor and assignment

A copy constructor is used to initialize a newly declared variable from an existing variable. This makes a deep copy like assignment, but it is somewhat simpler:

  1. There is no need to test to see if it is being initialized from itself.
  2. There is no need to clean up (eg, delete) an existing value (there is none).
  3. A reference to itself is not returned.