Copy constructors

 

Copy constructor:

Copy constructor is a parameterized constructor using which one object can be copied to another object.

Syntax:

class classname

{

            private:

                        ---------

            pubic:

                        classname(classname & object)

                        {

                                    ------------

                        }

};

Example:

class simple

{

            private:

                        int a;

            pubic:

                        simple(simple &s)

                        {

                                    s.a=10;

                        }

};

 

·       Copy constructor is invoked explicitly.

·       When a object is passed to a function, copy constructor is automatically called.

·       Copy constructor is invoked when functions return value is object.

·       When new object is created and equated to an already existing object in the declaration statement.

Ex:

      Name n1(100,200);

      Name n2=n1;                       // copy constructor is invoked

·       When new object is declared and existing object is passed as a parameter to it in the declaration.

Ex:

      Name n1(100,200);

      Name n2(n1);                      // copy constructor is invoked

Comments