Posts

Showing posts from 2020

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; . . .

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);     CopyDem