Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 550
sgryzko Avatar asked Feb 20 '14 22:02

sgryzko


People also ask

Is it possible to call base method without creating an instance?

Static method Normally you'd want to either have function calls, or to create an object on which you call its methods. You can however do something else: call a method in a class without creating an object.

How can we avoid a method from being inherited?

You could use other extension methods than subclassing in this case. For example, you might want to consider using events or delegates to extend the behavior instead of allowing the object to be subclasses. Trying to do what you are accomplishing is basically trying to prevent the main goals of inheritance.

Can a base class pointer call methods in the derived class?

When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.

Can you call the base class method without creating an instance in OOP?

Static Method Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.


2 Answers

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.

like image 195
David Rodríguez - dribeas Avatar answered Sep 26 '22 13:09

David Rodríguez - dribeas


You could also just throw an exception if the invalid method is called on the derived class. It doesn't catch the bug at compile time but at least it prevents it from accidentally being used a runtime.

Class B : public Base
{
   ...

   public:
      void OnlyMakesSenseOnA() { throw Exception(); }
}
like image 20
sgryzko Avatar answered Sep 30 '22 13:09

sgryzko