THe problem is that you have a non virtual foo()
so that A::bar()
will call the only foo()
it knows, being A::foo()
, even if it's B that invokes it.
Try:
class A {
public:
A() { foo(); }
virtual ~A() { foo(); } // <<---------- recommendation
virtual void foo() { cout << 3; } // <<<--------- solves it
void bar() { foo(); }
};
class B : public A {
void foo() override { cout << 2; } // <<---------- recommendation
};
Additional infos:
Making foo()
virtual in the base class allows each class to override this function, and be sure that the foo()
that is invoked is will be the foo()
corresponding to the object's real class.
It's a good practice then to use the keyword override
in the derived classes: it's not mandatory, but in case you make a typo in the functions signature, you'll immediately notice with a compile-time error message.
Another good practice is to make your base class destructor virtual if you have at least one virtual function in the class.
A final remark: in B, foo()
's private. This is legal, but it's weird because the inheritance says that B is a kind of A, but you can't use B objects exactly as an A object.