When a virtual method is called through a base pointer or a base reference pointing to a derived class object, base method is invoked first and then the derived method is invoked. Could someone explain why this behavior is implemented instead of directly calling the derived class method?
class Parent
class Parent{
private:
int money;
public:
void set_money(const int& m){
money = m;
}
virtual const int& get_money() const{
std::cout << "Parent version\n";
return money;
}
};
class Child
class Child : public Parent{
private:
int my_money;
mutable int family_money;
public:
void set_money(const int& m){
my_money = m;
}
const int& get_money() const{
family_money = my_money + Parent::get_money();
std::cout << "Child version\n";
return family_money;
}
void set_parent_money(const int& m){
Parent::set_money(m);
}
};
main
int main(){
Child c;
c.set_parent_money(20);
c.set_money(50);
Parent *p = &c;
cout << "Pointer " << p->get_money() << endl;
Parent& pr = c;
cout << "Reference " << pr.get_money() << endl;
Parent po = c;
cout << "Object " << po.get_money() << endl;
return 0;
}
Output
Parent version
Child version
Pointer 70
Parent version
Child version
Reference 70
Parent version
Object 20