Given the code below, shouldn't Calling B be printed, not Calling A? Isn't the runtime type of a a B and hence the virtual call should result in a call to B::operator= (as virtual calls are determined by the left operand)?
#include <iostream>
class A
{
public:
virtual A& operator=(const A& a_) { std::cout << "Calling A" << std::endl; }
};
class B : public A
{
public:
virtual B& operator=(const B& b_) { std::cout << "Calling B" << std::endl; }
};
int main() {
B b1;
B b2;
A& a = b1;
a = b2; // Prints "Calling A", should be "Calling B"?
return 0;
}
a = b2; is not a virtual call.
The reason for this is that B::operator=(const B&) does not override A::operator=(const A&), because their signatures are different.
You can use override to make the compiler automatically check these things for you.
Using override does two things:
The virtual method you have in B (B::operator=(const B&)) doesn't override the one in A (A::operator=(const A&)). I am guessing what you've written is an overload, therefore, compiler can't know such a method exists since you are using an A reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With