0

I'm learning C++ and I came across this problem while learning operator overloading:

I defined a complex class:

class Complex {
private:
    double real, imag;

public:
    Complex() = default;

    Complex(double real,double imag): real(real), imag(imag) {
        std::cout << "Double constructor" << std::endl;
    }

//    Complex(Complex &other) {
//        this->real = other.real;
//        this->imag = other.imag;
//        std::cout << "Copy constructor" << std::endl;
//    }

    Complex operator+(Complex &other) {
            return Complex(real+other.real, imag+other.imag);
    }

    ~Complex() {
        std::cout << "Desctuctor called: " << real << std::endl;
    }
};

With the copy constructor commented out, this code will work, but it won't otherwise. The error it gives is, on constructing a Complex object in the operator+ function, there's no appropriate constructor to call.

I wonder, why the compiler gives such error? Also, when I comment out the copy constructor, I guess the default copy constructor is called when I do something like

C3 = C1 + C2;

Is that correct?

I couldn't find anything useful to this on SO (or maybe I'm too dumb to see it through), any help is greatly appreciated!

Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83

1 Answers1

1

Your operator+ function returns a Complex by value, so it has to call the copy constructor.

Without your custom constructor, the compiler generates a default copy constructor, which works just fine (it performs a memberwise copy).

With your custom constructor, the compiler will not generate a default copy constructor. However, your custom copy constructor has an unusual type:

Complex(Complex &other)

requires an lvalue as input. It cannot be used to copy temporaries.

The compiler-generated copy constructor takes const Complex &other instead, which can bind to temporary values.

melpomene
  • 84,125
  • 8
  • 85
  • 148