I have the following code in C++:
#include <iostream>
using namespace std ;
class A{
public:
void m1(){
cout << "A" << endl;
}
virtual void m2(){
cout << "A" << endl;
}
void m3(){
cout << "A" << endl;
}
};
class B: public A{
public:
void m1(){
cout << "B" << endl ;
}
virtual void m2(){
cout << "B" << endl;
}
virtual void m3(){
cout << "B" << endl;
}
};
int main(){
A∗ p = new B() ;
p−>m1() ;
p−>m2() ;
p−>m3() ;
}
What will each call in main() produce? I’m see that A B A, but don't know how to explain this in a detail.
A::m1andA::m3are not virtual, so the code callsA::m1andA::m3.A::m2is virtual, so the call goes to the overriding function,B::m2. Marking functions virtual in a derived class doesn't affect the virtualness in the base class.main(), but is really bad for code reusability.)