Constructors With Default Arguments, Copy Constructor

Explain Constructors With Default Arguments, Copy Constructor with Example and Program



Constructors with default arguments:-


It is possible to define constructors with default arguments.   For ex. The constructor ‘complex’ can be defined as follows
            complex (float real, float imag=0);

    The default value of the argument imag is zero
Then the following statements, complex C(5.0); Assigns the value 5.0 to the real variable and 0.0 to imag by default however the statement/ complex C(2.0,3.0); assigns 2.0 to real and 3.0 to imag. Here the actual parameter 3.0 overrides the default value (0.0)

Copy constructor:- 

A copy constructor is a special constructor in the C++ programming language used to create a new object as a copy of an existing object. This constructor takes a single argument: a reference to the object to be copied.
Normally the compiler automatically creates a copy constructor for each class (known as an implicit copy constructor) but for special cases the programmer creates the copy constructor, known as an explicit copy constructor. In such cases, the compiler doesn't create one
There are four instances when a copy constructor is called:
1.    When an object is returned by value
2.    When an object is passed (into a function) by value as an argument
3.    When an object is constructed based on other object (pf same class)
4.    When compiler generates a temporary object (as in 1 and 2 above; as in explicit casting, etc...)

  Constructors of a class can be invoked by using existing objects of the class.
Syntax :-  obect . class-name :: constructor-function-call ;
#include <iostream.h>
#include<conio.h>
class code
{        int d;
    public:
    code()
    {cout<<"\ndefault constructor";
    }    // default constructor
    code(int a)  //constructor -2
    { d=a;
      cout<<"\nparameterized contrctr";
    }
    code(code &x)//copy constructor
    { d=x.d;
     cout<<"\ncopy cntrctr";
    }
    void display( )
       { cout<<"\nd="<<d<<endl;
       }
};
void main( )
{       clrscr();
    code A(100);    //calls constructor - 2
    code B(A);        //calls copy constructor
    code C=A;        //calls copy constructor
    code D;        //calls no argument constructor
    D=A;// It is assignment not initialization hence no copy const. will be called
    A.display ( );
    B.display ( );
    C.display ( );
    D.display ( ) ;
    getch();
}



Labels: