Copy constructor in C++ (Part 1)

In C++, the copy constructor is called when the object is not already created.

For example,

CopyDemo o1, o2;
CopyDemo MyObj = o1;  // Here MyObj is created and at the same time initialized.

o1 = o2 // Here o1 is already created, so assignment operator function is called.

When initializing MyObj, copy constructor is called and when initializing o1, assignment operator function is called.

The other scenarios are when we pass object to another function and when we return object from a function.

Examples:

func(MyObj);
MyObj = getObj();

The example code is as below:

#include <iostream>

using namespace std;

class CopyDemo {
    public:
        CopyDemo(int initValue) {
            ptr = new int;
            *ptr = initValue;
        }

        CopyDemo(const CopyDemo &obj) {
            cout << "Calling copy constructor\n";
            ptr = new int;
            *ptr = *obj.ptr;
        }

    private:
        int *ptr;
};

int main()
{
    CopyDemo o1(10);
    CopyDemo o2 = o1;
    return 0;
}

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

Copy constructor in C++ (Part 2)