I know about the basic concept of virtual function and run-time call. But i tried
running some piece of code which confused me
class A {
public:
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;
}
};
class B : public A {
public:
B& operator=(char) {
cout << "B& B::operator=(char)" << endl;
return *this;
}
virtual B& operator=(const B&) {
cout << "B& B::operator=(const B&)" << endl;
return *this;
}
};
int main() {
B b1;
B b2;
A* ap1 = &b1;
A* ap2 = &b1;
*ap1 = 'z';
*ap2 = b2;
}
Running this program give me the following output:-
A& A::operator=(char) //expected output
A& A::operator=(const A&) //Why this Output? in case of *ap2 = b2;
b2 is an object of B type but still it goes in virtual A& operator=(const A&)
and not virtual B& operator=(const B&). Why is this so ?
Because
virtual B& operator=(const B&)does not overridevirtual A& operator=(const A&); the arguments are different.