1

I am trying to understand the concept of copy constructors in C++. I have written the following program:

#include<iostream>
using namespace std;

class Box{
    private:
        int d;
    public:
        Box(int i){
            cout << "Constructor" << endl;
            d = i;
        }
        Box(const Box &old){
            cout << "Copy Constructor" << endl;
            d = old.d;
        }
        int getd(){
            return d;
        }
        ~Box(){
            cout << "Destructor" << endl;
        }
        Box operator+(const Box& op){
            Box c(15);
            c.d = d + op.d;
            return c;
        }
};

int main(){
    Box a(10);
    Box b = a;
    Box c = a+b;
    cout << c.getd() << endl;
    return 0;
}

The output of this program is as follows:

Constructor
Copy Constructor
Constructor
20
Destructor
Destructor
Destructor

I don't understand why the copy constructor isn't getting called for the third line in the main function. I think that there should be a call to the copy constructor as operator+ function returns by value.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Surajeet Bharati
  • 1,363
  • 1
  • 18
  • 36

1 Answers1

3

The compiler is optimising out the copy constructor call here, because the standard explicitly allows that copy to be "elided". What would be the point in such a copy, really?

You're absolutely right though, in that it's an opportunity for invocation of the copy constructor, and the compiler could do it. In fact, the standard does require that invoking the copy constructor be valid here.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055