What is difference between protected and private derivation in c++

Possible Duplicate:
Difference between private, public and protected inheritance in C++

What is difference between deriving as protected or private in c++? i am not able to figure out, since both seem to restrict base class member access from derived class object


Let's consider a code example showing what would be allowed (or not) using different levels of inheritance:

 class BaseClass {};

 void freeStandingFunction(BaseClass* b);

 class DerivedProtected : protected BaseClass
 {
     DerivedProtected()
     {
         freeStandingFunction(this); // Allowed
     }
 };

DerivedProtected can pass itself to freeStandingFunction because it knows it derives from BaseClass .

 void freeStandingFunctionUsingDerivedProtected()
 {
     DerivedProtected nonFriendOfProtected;
     freeStandingFunction(&nonFriendOfProtected); // NOT Allowed!
 }

A non-friend (class, function, whatever) cannot pass a DerivedProtected to freeStandingFunction , because the inheritance is protected, so not visible outside derived classes. Same goes for private inheritance.

 class DerivedFromDerivedProtected : public DerivedProtected
 {
     DerivedFromDerivedProtected()
     {
         freeStandingFunction(this); // Allowed
     }
 };

A class derived from DerivedProtected can tell that it inherits from BaseClass , so can pass itself to freeStandingFunction .

 class DerivedPrivate : private BaseClass
 {
      DerivedPrivate()
      {
          freeStandingFunction(this); // Allowed
      }
 };

The DerivedPrivate class itself knows that it derives from BaseClass , so can pass itself to freeStandingFunction .

class DerivedFromDerivedPrivate : public DerivedPrivate
{
     DerivedFromDerivedPrivate()
     {
          freeStandingFunction(this); // NOT allowed!
     }
};

Finally, a non-friend class further down the inheritance hierarchy cannot see that DerivedPrivate inherits from BaseClass , so cannot pass itself to freeStandingFunction .


Use this matrix (taken from here) to decide the visibility of inherited members:

inheritancemember  |     private     |   protected   |   public
--------------------+-----------------+---------------+--------------
private             |  inaccessible   |    private    |  private
protected           |  inaccessible   |    protected  |  protected
public              |  inaccessible   |    protected  |  public
--------------------+-----------------+---------------+--------------

Example 1:

class A { protected: int a; }
class B : private A {};       // 'a' is private inside B

Example 2:

class A { public: int a; }
class B : protected A {};     // 'a' is protected inside B

Example 3:

class A { private: int a; }
class B : public A {};        // 'a' is inaccessible outside of A

private只允许声明的类访问它protected允许类和派生/子类访问,就像它是私有的一样

链接地址: http://www.djcxy.com/p/78548.html

上一篇: c ++继承语法

下一篇: c ++中的protected和private派生之间有什么区别?