Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance: Selecting which base class methods to inherit [closed]

I have a class Base and want to write a class Derive which inherits only some of the member functions from Base. Is there any convenient way to do this?

For example,

class Base
{
   ...
   void fooA();
   void fooB();
   ...
}

I wish to define a class Derive which inherits all members except fooB from Base.

like image 685
C. Wang Avatar asked Nov 28 '25 18:11

C. Wang


1 Answers

When you derive a subclass from a base class, you inherit all member functions from the base class (except the constructors & destructor, which are never inherited). You cannot pick and choose which members to derive.

However, this seems like an XY Problem. Depending on what you're really trying to do, you might be able to accomplish your actual goals.

You could change the visibility of a derived method:

class Derived : public Base
{
private: 
  using Base::fooB; // fooB() is now private
};

You could use private inheritance, and then make public only those methods you wish to provide:

class Derived : private Base
{
public:
  using Base::fooA;  // Only fooA() is public here
};

You could avoid inheritance altogether and encapsulate Base instead, and provide bridge methods for the resources in Base you wish to provide access for:

class Derived 
{
Base mBase; // private
public:
  void fooA() { mBase.fooA(); }
};

However, note that in the later two cases you lose some of the benfits of polymorphism. In order to have a Base* point to something that is actually a Derived, you must use public inheritance.

like image 69
John Dibling Avatar answered Nov 30 '25 10:11

John Dibling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!