Search code examples
c++derived-class

Is there a way to prevent a base class method from being called on an instance of a derived class?


I have a base class with a bunch of functionality and a derived class that extends that class but there are a few methods in the base class that don't make sense on the derived class.

Is it possible to do something to prevent these method(s) from being used by the derived class?

Class A
{
   ...

   public:
      void SharedMethod();
      virtual void OnlyMakesSenseOnA();
}

Class B : public Class A
{
   ...

   public:
      void OnlyMakesSenseOnB();
}

The following obviously doesn't work but is it possible to do something similar so that the compiler doesn't allow a certain base class method to be called?

Class B : public Class A
{
   ...

   public:
      void OnlyMakesSenseOnA() = 0;
}

Solution

  • No, and this is completely wrong. If the member function is not callable in the derived type you are breaking the Liskov Substitution Principle. Consider whether this is the correct inheritance relationship. Maybe you want to extract SharedMethod to a real base and provide two separate unrelated A and B types.