I'm a bit lost in C++ operators. I'd like to enforce the assignment operator for two different classes, i.e. so one can assign one to each other:
class A {
public:
virtual A &operator =(const A &a) = 0;
};
class B : public A {
public:
virtual A &operator =(const A &a) override {
std::cout << "B" << std::endl;
return *this;
}
};
class C : public A {
public:
virtual A &operator =(const A &a) override {
std::cout << "C" << std::endl;
return *this;
}
};
int main(int argc, char *argv[])
{
B b;
C c;
b = c;
// leads to a linker error: undefined reference to `A::operator=(A const&)'
//B b2;
//b = b2;
}
The first assignment seems to do the job, "B" is called. Similarly, for "c = b", "C" is called. However when I uncomment the second part, I get the linker error. If I define A's operator like:
virtual A &operator =(const A &a) {
std::cout << "A" << std::endl;
return *this;
}
I get "B", "A". Huh? Can somebody explain why "A" is needed when two B's are assigned but not when B <- C is?
std::endl
does?'\n'
ends a line. – Cult