However, you can declare any copy assignment operator
as virtual. The following example demonstrates this:
#include <iostream>
using namespace std;
struct A {
A& operator=(char) {
cout << "A& A::operator=(char)" << endl;
return *this;
}
virtual A& operator=(const A&) {
cout << "A& A::operator=(const A&)" << endl;
return *this;
}
};
struct B : A {
B& operator=(char) {
cout << "B& B::operator=(char)" << endl;
return *this;
}
virtual B& operator=(const A&) {
cout << "B& B::operator=(const A&)" << endl;
return *this;
}
};
struct C : B { };
int main() {
B b1;
B b2;
A* ap1 = &b1;
A* ap2 = &b1;
*ap1 = 'z';
*ap2 = b2;
C c1;
// c1 = 'z';
}
The following is the output of the above example:
A& A::operator=(char)
B& B::operator=(const A&)
The assignment
*ap1 = 'z' calls
A&
A::operator=(char). Because this operator has not been declared
virtual,
the compiler chooses the function based on the type of the pointer
ap1.
The assignment
*ap2 = b2 calls
B& B::operator=(const &A).
Because this operator has been declared
virtual,
the compiler chooses the function based on the type of the object
that the pointer
ap1 points to. The compiler would
not allow the assignment
c1 = 'z' because the implicitly
declared copy assignment operator declared in class
C hides
B&
B::operator=(char).