سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

If I am right, then what you are looking is Inheritance. Which means if A inherits B, it inherits B's methods and properties, if and only they are cleared protected or public.

Check these links:

  1. http://www.cplusplus.com/doc/tutorial/inheritance/
  2. http://www.youtube.com/watch?v=gq2Igdc-OSI

You can make fooB private and it will be invisible in the derived class. Learn about private/protected/public modifiers and about public/private/protected inheritance. These are tools you need.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top