user6245072 user6245072 - 1 month ago 9
C++ Question

How to make an inherited virtual function not usable?

I have an abstract base class which declares a pure virtual function (

virtual method() = 0;
). Some of the inherited classes specialize and use this method but there's one of those inherited classes in which I don't want to make this method usable. How do I do it? Is making it private the only choice?

Answer

Well, you could throw that will make tacking where it is called easier.

void method() override { throw /* whatever */ ; } 

Dynamic polymorphism is a runtime property. Hence a runtime error. If you look after something that will trigger at compile time, you need static polymorphism.

template<typename Child>
struct Parent {
    void callMe() {
        static_cast<Child*>(this)->callMeImpl();
    }
};

struct SomeChild : Parent<SomeChild> {

};

Now, if you try to call callMe form the parent that is extended by SomeChild, it will be a compile time error.

You can also hold pointer to the parent just like dynamic polymorphism, as the parent will call the child function