In C++ why the pure virtual method mandates its compulsory overriding only to its immediate children (for object creation), but not to
I found one mechanism, where at least we are prompted to announce the overridden method explicitly. It's not the perfect way, but at least somewhat near.
Suppose, we have few pure virtual methods in class B (base):
class B {
virtual void foo () = 0;
virtual void bar (int) = 0;
};
Among them, I want foo() to be overridden by the whole hierarchy, then abstract foo() 1 level up for simplicity:
class Register_foo {
template // this matches the signature of 'foo'
Register_foo (void (T::*)()) {}
};
class Base : 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 its foo inside its every constructor explicitly. e.g.:
struct D : B {
D () : Register_foo(&D::foo) {}
D (const D &other) : Register_foo(&D::foo) {}
virtual void foo () {};
};
This registration mechanism has nothing to do with the business logic. But at least inside the constructor of any child class it would be mentioned that, which foo it's using.
Though, the child class can choose to register using its own foo or its parent's foo, but at least that is announced explicitly.