Let’s say I have the following classes:
class A {
public:
virtual void foo() {
bar();
}
protected:
virtual void bar() {
// Do stuff
}
}
class B : public A {
protected:
virtual void bar() {
// Do other stuff
}
}
If I have an instance of B and call the foo method, which bar method would get called? And is this compiler specific?
Thanks
The
A::foowill callB::barif you have an instance ofB. It does not matter if the instance is referenced through a pointer or a reference to a base class: regardless of this,B‘s version is called; this is what makes polymorphic calls possible. The behavior is not compiler-specific: virtual functions behave this way according to the standard.