Reputation: 7620
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
Upvotes: 24
Views: 16234
Reputation: 390
You can't, but you can get around it. In this case you can add a true
default bool argument to the A constructor, and pass a false
to it in B:
class A
{
public:
A(bool construct = true) {
if (!construct) return;
bar();
}
virtual void bar() { cout << "A::bar" << endl; }
};
class B : public A
{
public:
B() : A(false) { bar(); }
void bar() override { cout << "B::bar" << endl; }
};
int main()
{
A a;
B b;
}
Output:
A::bar
B::bar
Upvotes: 0
Reputation: 727137
The A::foo
will call B::bar
if you have an instance of B
. 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.
Upvotes: 32