1

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:

  1. When we initialize the object with another existing object of the same class type.
  2. When the object of the same class type is passed by value as an argument.
  3. 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;
}
Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
  • 2
    `Complex operator = (const Complex &object ){` misses `return *this;` so your program has undefined behavior. It should probably also be `Complex& operator = (const Complex &object ){` - You don't want to return a copy, but a reference to `*this`. [example](https://godbolt.org/z/3rM6Kv) – Ted Lyngmo Dec 11 '20 at 17:44
  • 1
    Look at [Copy elision and (N)RVO](https://en.cppreference.com/w/cpp/language/copy_elision). – Jarod42 Dec 11 '20 at 17:45
  • 1
    gcc flag `-fno-elide-constructors` might also help. – Jarod42 Dec 11 '20 at 17:46

0 Answers0