i am having problem understanding how the output of this code comes out like this:
#include<iostream>
using namespace std;
class three_d
{float x,y,z;
public:
three_d(){x=y=z=0;cout<<"\n\tDefault Constructor";}
three_d(float a,float b,float c){x=a;y=b;z=c;cout<<"\n\tOverloaded Constructor";}
three_d(const three_d &obj){x=obj.x;y=obj.y;z=obj.z;cout<<"\n\tCopy Constructor";}
three_d operator+(three_d op2);
three_d operator=(three_d op2);
void show();
~three_d(){cout<<"\n\tDestructor Working !!";}
};
three_d three_d::operator+(three_d op2)
{
x=x+op2.x;
y=y+op2.y;
z=z+op2.z;
return *this;
}
three_d three_d::operator=(three_d op1)
{
x=op1.x;
y=op1.y;
z=op1.z;
return *this;
}
void three_d::show()
{
cout<<"\n\n\tValues are : x="<<x<<" y="<<y<<" and z="<<z<<"\n";
}
int main()
{
three_d ob1(2.1,2,2.2);
three_d ob2(1,1,1), ob3;
ob3=ob1+ob2;
ob1.show();
ob2.show();
ob3.show();
return 0;
}
The output comes as :
1. Overloaded Constructor
2. Overloaded Constructor
3. Default Constructor
4. Copy Constructor
5. Copy Constructor
6. Destructor Working !!
7. Copy Constructor
8. Destructor Working !!
9. Destructor Working !!
10. Values are : x=3.1 y=3 and z=3.2
11. Values are : x=1 y=1 and z=1
12. Values are : x=3.1 y=3 and z=3.2
13. Destructor Working !!
14. Destructor Working !!
15. Destructor Working !!
So my questions are:
- In the 5th line of output what is this copy constructor for? is it for *this pointer (but as it is a pointer i dont think it needs a copy constructor)? The fourth line is for object op2(i suppose) ?
- If above statement is true when overloading "=" why is only one copy constructor used(when it also have a returning value ?
- When is the temporary(returning) object destructed ?
- Please explain how the output is ordered like this.
Even if i change the overloaded "+" to something like this :
three_d three_d::operator+(three_d op2)
{three_d temp;
temp.x=x+op2.x;
temp.y=y+op2.y;
temp.z=z+op2.z;
return temp;
}
the output of copy constructor for "=" remains same(though values will be changed) i.e only 1 copy constructor for "=". However I think there must be 2 copy constructors for "=" 1 for op1 object and other for *this .
If i use simple assignment in main like :
ob3=ob1;
the copy constructor is called twice as expected.
Please explain.