AlwaysLearning AlwaysLearning - 3 months ago 9
C++ Question

Inheriting the virtual specifier of base class's member function

The following code is based on the example on page 298 of C++ Templates: the Complete Guide. I removed the parts not relevant to my question.

class Virtual {
public:
virtual void foo() {
}
};

class Base : private Virtual {
public:
void foo() {
std::cout << "Base::foo()" << '\n';
}
};

class Derived : public Base {
public:
void foo() {
std::cout << "Derived::foo()" << '\n';
}
};

int main()
{
Base *p = new Derived;
p->foo(); // calls Derived::foo()
}


I do not understand how the call
p->foo()
ends up calling
Derived::foo
. More concretely, the static type of
p
is
Base*
.
Base::foo
is non-virtual. Now,
Base
privately inherits from 'Virtual', which has its own
foo
and it looks as if
Base::foo
somehow gets the
virtual
specifier from
Virtual::foo
. What is actually going on here?

Answer

The virtualness of foo is inherited from the base class Virtual.

In fact, writing virtual in Derived::foo will be superfluous and many developers will omit it. You cannot undo virtualness once you've marked that function as virtual in a base class.

You can force a call of Base::foo by writing p->Base::foo(); but that's an ugly contrivance.

Comments