Copy constructor in C++ (Part 2)

Now, the important question comes is regarding the signature of copy constructor. That is, why copy constructor takes a reference as parameter.

Let's copy by value from previous example.

CopyDemo(const CopyDemo obj) {
    ptr = new int;
    *ptr = *obj.ptr;
}

Now from main(),

CopyDemo o2 = o1;

Let me explain in detail. We have called copy constructor to copy o1 to o2. But, since we are passing by value, first o1 has to be copied to obj. So internally, statement will be,

const CopyDemo obj = o1;

Now, what happens is again copy constructor is invoked. Already, we can sense some problem, copy constructor is called again. Internally, the statement is repeated again.

const CopyDemo obj = o1;

This goes into a recursive loop and following statements get repeated till stack overflow happens and ultimately program crashes.

const CopyDemo obj = o1;
const CopyDemo obj = o1;
const CopyDemo obj = o1;
.
.
.

Comments

Popular posts from this blog

Synchronization primitives: Mutex and Semaphore (Serialization & Mutex problems using Semaphore) - Article 6

Synchronization primitives: Mutex and Semaphore (Readers & Writers problem) - Article 8