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!