1

I am not able to understand how the values of member variables are getting copied even though the constructor is not getting called in the below program.

#include <iostream>

using namespace std;

class myclass
{
    public:
        int x;
        int y;

        myclass(int a, int b)
        {
            cout << "In Constructor" << endl;
            x = a;
            y = b;
        }

        ~myclass()
        {
            cout << "In Destructor" << endl;
        }

        myclass(const myclass &obj)
        {
            cout << "In Copy Constuctor " << obj.x << " " << obj.y << endl;
            x = obj.x;
            y = obj.y;
        }

        myclass &operator=(const myclass &obj)
        {
            cout << "In Operator Overloading" << obj.x << obj.y << endl;
            x = obj.x;
            y = obj.y;

            return *this;
        }
};

int main()
{
    myclass obj1 = myclass(2, 3);
    cout << "obj1.x : " << obj1.x << "obj1.y" << obj1.y << endl;
}

Output:
In Constructor
obj1.x : 2obj1.y3
In Destructor

I understood that due to Return Value Optimization, copy constructor is not getting called. But I didn't understand how obj1 is getting values 2 and 3. Can any one please help me to understand this or how Return Value Optimization will work behind the scenes.

kadina
  • 5,042
  • 4
  • 42
  • 83

1 Answers1

2

The values aren't getting copied, because they don't need to be copied. Instead, the values which would have been copied are initialized in place. Copy elision means that the compiler essentially turns this:

myclass obj1 = myclass(2, 3);

Into this:

myclass obj1(2, 3);

So no extra object is constructed which needs to be copied.

Note that RVO, which you've referred to, is a form of copy elision. But this specific case of copy elision is not RVO.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274