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.