mikestaub mikestaub - 9 months ago 28
C++ Question

Do ALL virtual functions need to be implemented in derived classes?

This may seem like a simple question, but I can't find the answer anywhere else.

Suppose I have the following:

class Abstract {
virtual void foo() = 0;
virtual void bar();

class Derived : Abstract {
virtual void foo();

Is it ok that class Derived does not implement the bar() function?
What if not ALL of my derived classes need the bar() function, but some do.
Do all of the virtual functions of an abstract base class need to be implemented in the derived classes, or just the ones that are pure virtual?

Answer Source

Derived classes do not have to implement all virtual functions themselves. They only need to implement the pure ones.1 That means the Derived class in the question is correct. It inherits the bar implementation from its ancestor class, Abstract. (This assumes that Abstract::bar is implemented somewhere. The code in the question declares the method, but doesn't define it. You can define it inline as Trenki's answer shows, or you can define it separately.)

1 And even then, only if the derived class is going to be instantiated. If a derived class is not instantiated directly, but only exists as a base class of more derived classes, then it's those classes that are responsible for having all their pure virtual methods implemented. The "middle" class in the hierarchy is allowed to leave some pure virtual methods unimplemented, just like the base class. If the "middle" class does implement a pure virtual method, then its descendants will inherit that implementation, so they don't have to re-implement it themselves.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download