0

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..??

Community
  • 1
  • 1
user436212
  • 67
  • 4

1 Answers1

2

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;

Zitrax
  • 19,036
  • 20
  • 88
  • 110
  • your answer might be correct, if it is all that smart guys in comments are wrong about duplicate. – Andrey Sep 09 '10 at 12:33
  • What difference is there between a "has a" private inheritance and aggregation then ? – Cedric H. Sep 09 '10 at 12:37
  • +1, as the first line is the actual problem. Now, private inheritance models *implemented in terms of*, not *has a*, that would be modeled with composition. – David Rodríguez - dribeas Sep 09 '10 at 12:46
  • @Cedric With aggregation you can use several objects, like "has many", but with private inheritance you are locked to just one. – Zitrax Sep 09 '10 at 12:49
  • @Cedric: private inheritance allows you to override virtual functions and access protected members of the base class. – Mike Seymour Sep 09 '10 at 12:50
  • @David True I updated and changed "is a" to "implemented in terms of". – Zitrax Sep 09 '10 at 12:51
  • @Andrey: It is a duplicate of the other question. The answer is quite convoluted but can be described in simple terms here with something in the lines of *the private base class is not accessible and thus you cannot convert a pointer to derived to a pointer to base*. – David Rodríguez - dribeas Sep 09 '10 at 13:26