开发者

Typical problem on Inheritance [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Why is this not allowed in C++?

Why is this not allowed in C++...??

class base
{
  private:

  public:
      void func()
         {
              cout<<"base";
         }  


};

class derived : private base
{
  private:


  public:
            void func()
         {
              cout<<"derived";
              }


};

int main()
{
base * ptr;
ptr = new derived;
((开发者_开发百科derived *)ptr)->func();
return 0;
}

I am getting an error

**61 C:\Dev-Cpp\My Projects\pointertest.cpp `base' is an inaccessible base of `derived'** 

My question is that since func() is defined public in derived class and the statement ((derived *)ptr)->func(); is trying to display the func() of derived..Why is there an accessible issue due to mode of inheritance..How does mode of inheritance(private) affects the call although I already have public derived func() in derived class..?

If mode of inheritance is changed to public I get my desired result..But a case where func() is private in base(so as func() of base is not inherited) and also func() is public in derived and mode of inheritance is public why still am I getting my desired result..Shouldn I be getting an Compile error as in the previous case ??

I am totally confused ..Please tell me how the compiler works in this case..??


You can't let the base pointer point to the derived object when there is private inheritance.

Public inheritance expresses an isa relationship. Private inheritance on the other hand expresses a implemented in terms of relationship

Ther compile error refers to the line: ptr = new derived;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜