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++?
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
virtualmethods in the baseclass B:Among them, suppose we want only
foo()to be overridden by the whole hierarchy. For simplicity, we have to have avirtualbase class, which contains that particular method. It has a template constructor, which just accepts the type same as that method.Every subsequent child class in the hierarchy would have to register a
fooinside its every constructor explicitly. e.g.:This registration mechanism has nothing to do with the business logic. Though, the child
classcan choose to register using its ownfooor its parent’sfooor even some similar syntax method, but at least that is announced explicitly.