Force all classes to implement / override a 'pure virtual' method in multi-level inheritance hierarchy

iammilind picture iammilind · Feb 28, 2012 · Viewed 11.4k times · Source

In C++ why the pure virtual method mandates its compulsory overriding only to its immediate children (for object creation), but not to the grand children and so on ?

struct B {
  virtual void foo () = 0;
};
struct D : B {
  virtual void foo () { ... };
};

struct DD : D {
  // ok! ... if 'B::foo' is not overridden; it will use 'D::foo' implicitly
};

I don't see any big deal in leaving this feature out.
For example, at language design point of view, it could have been possible that, struct DD is allowed to use D::foo only if it has some explicit statement like using D::foo;. Otherwise it has to override foo compulsory.

Is there any practical way of having this effect in C++?

Answer

iammilind picture iammilind · Mar 12, 2012

I found one mechanism, where at least we are prompted to announce the overridden method explicitly. It's not the perfect way though.

Suppose, we have few pure virtual methods in the base class B:

class B {
  virtual void foo () = 0;
  virtual void bar (int) = 0;
};

Among them, suppose we want only foo() to be overridden by the whole hierarchy. For simplicity, we have to have a virtual base class, which contains that particular method. It has a template constructor, which just accepts the type same as that method.

class Register_foo {
  virtual void foo () = 0; // declare here
  template<typename T>  // this matches the signature of 'foo'
  Register_foo (void (T::*)()) {}
};
class B : public virtual Register_foo {  // <---- virtual inheritance
  virtual void bar (int) = 0;
  Base () : Register_foo(&Base::foo) {}  // <--- explicitly pass the function name
};

Every subsequent child class in the hierarchy would have to register a foo inside its every constructor explicitly. e.g.:

struct D : B {
  D () : Register_foo(&D::foo) {}
  virtual void foo () {};
};

This registration mechanism has nothing to do with the business logic. Though, the child class can choose to register using its own foo or its parent's foo or even some similar syntax method, but at least that is announced explicitly.