Copy Constructor

Explain what is copy constructor and what is the difference between copy constructor and overloaded assignment operator

Questions by shyamkumar1221

Showing Answers 1 - 6 of 6 Answers

amitmanish

  • Mar 4th, 2011
 

Copy contructor is parameterised constructor with a argument which is a reference to an object of the class.

Why we need a reference?
the answer is that if we don't use a reference and instead use an object to pass an argument it will again need a call to the copy constructor to create a copy which in turn again does the same, this leads to an infinite chain of such calls.

Assignment operator as well as copy constructor do a shallow copy, i.e for an example as below instead of putting the address of the variable o4.a of into o4.ptr it copies the address stored in o1.ptr into o4.ptr. But this behaviour can be changed by writting a custom module for both.

The following code illustrates where copy constructor is invoked and where an assignment operator is invoked.

#include<iostream.h>
class A
{
    public:

    int a;
    int *ptr;

    A(){a = 10; ptr = &a;}
    A(A &b) // if we use A(A b) here this invokes copy constructor recursively
    {
        a = b.a;
        ptr = &a; //changing the default behavior of shallow copying which woud be
                       // an equivalent of ptr = b.ptr
    }
};

void main()
{
    A o1;
    A o2(o1);  //copy contructor
    A o3  =  o1; //copy contructor
    A o4;
    o4 = o1; //assignment operator

    cout<<o1.a<<'n';
    cout<<o1.ptr<<'n';

    cout<<o2.a<<'n';
    cout<<o2.ptr<<'n';

    cout<<o1.a<<'n';
    cout<<o1.ptr<<'n';

}


  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions