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

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

Is there anything you can do to prevent these methods from being used by the derived class?

Class A
{
   ...

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

Class B : public Class A
{
   ...

   public:
      void OnlyMakesSenseOnB();
}

Obviously, the following does not work, but is it possible to do something like this so that the compiler does not allow calling the base class method?

Class B : public Class A
{
   ...

   public:
      void OnlyMakesSenseOnA() = 0;
}
+4
source share
3 answers

, . - , . , . , SharedMethod A B.

+4

, , , , , :

Class Base
{
   ...

   public:
      void SharedMethod();
}

Class A : public Base
{
   ...

   public:
      void OnlyMakesSenseOnA();
}

Class B : public Base
{
   ...

   public:
      void OnlyMakesSenseOnB();
}

: @David , . B " " A, " . B A .

:

  • , T, x S.
  • x , ( Ts).
  • x , T, , , x .
  • S , S T.
+4

You can also just throw an exception if an invalid method is called in a derived class. It does not detect an error at compile time, but at least prevents its accidental use of the runtime.

Class B : public Base
{
   ...

   public:
      void OnlyMakesSenseOnA() { throw Exception(); }
}
+2
source

Source: https://habr.com/ru/post/1527996/


All Articles