简体   繁体   中英

how can a derived class function call a function of the base class?

Derived class function cannot access even the public members of the base class when the access specifier is private. But how is it that the function ' xyz ' of my derived class able to call ' showofb '? I even tried it by calling the function ' showofb ' in the constructor of C. In both cases it works. How is it able to call the function ' showofb ' ?

class B  
{  
    public:  
    B()  
    {  
        cout<<":B:"<<endl;  
    }  
    void showofb()  
    {  
        cout<<"show of b"<<endl;  
    }  
};

class C : private B  
{
public:  
   C()  
   {  
        cout<<":C:"<<endl;  
   }  
   void xyz()  
   {  
        showofb();  
   }  
};  

int main()  
{  
    C c1;  
    c1.xyz();  
}    

Private inheritance inherits the public members of the parent as the private members of the child. A class can call its own or inherited private members.

Consider this:

class B  
{  
    public:  
    B()  
    {  
        cout<<":B:"<<endl;  
    }  
    void showofb()  
    {  
        cout<<"show of b"<<endl;  
    }  
};  
class C : private B  
{
public:  
C()  {}
};  
class D : public B
{
 public:
    D(){};
}
int main()  
{  
    C c1;  
    c1.showofb();  // WONT WORK
    D d1;
    d1.showofb();  // WILL WORK
}    

B::showofb() is a public function. So it can be called by C . If you modify B to make showofb private, C will no longer be able to call it.

The private inheritance means that all public and protected members of B are inherited as private by C . So C can still call public and protected members of B , but any classes derived from C will not be able to call members of B .

user1001204, you appear to have a mistaken concept of private inheritance. That class C inherits from class B via private inheritance means that the inheritance relationship is hidden to anything that uses class C . Private inheritance does not hide the inheritance relationship inside Class C itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM