I am trying to code all possible ways of invoking a Copy Constructor in C++ using the below points.
Copy Constructor is called in the following scenarios:
- When we initialize the object with another existing object of the same class type.
- When the object of the same class type is passed by value as an argument.
- When the function returns the object of the same class type by value.
I am able to invoke Copy Constructor using the first two methods but not with the third one. I am returning an object by value from an overloaded operator function.
#include<iostream>
using namespace std;
class Complex {
int real;
int imaginary;
public:
Complex(int r = 0, int i = 0){
cout<<"Parameter Constructor Called - this "<<this<<endl;
real = r;
imaginary = i;
}
Complex(const Complex &object){
cout<<"copy constructor called - this "<<this<<endl;
this->real = object.real;
this->imaginary = object.imaginary;
}
Complex operator + (Complex const &object){
cout<<"+ operator overloaded function - this "<<this<<endl;
Complex result;
result.real = real + object.real;
result.imaginary = imaginary + object.imaginary;
cout<<"+ operator overloaded function - result "<<&result<<endl;
return result;
}
Complex operator = (const Complex &object ){
cout<<"= operator overloaded function - this "<<this<<endl;
real = object.real;
imaginary = object.imaginary;
}
};
int main()
{
Complex c1(10,5), c2(2, 4);
Complex c3 = c1; //Copy Constructor Invoked
Complex c4(c1); //Copy Constructor Invoked
Complex c5 = c1 + c2; //Copy Constructor Not Invoked, Why?
cout<<"address of c1 is " << &c1 << endl;
cout<<"address of c2 is " << &c2 << endl;
cout<<"address of c3 is " << &c3 << endl;
cout<<"address of c4 is " << &c4 << endl;
cout<<"address of c5 is " << &c5 << endl;
return 0;
}