views:

97

answers:

1

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

+1  A: 

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
your answer might be correct, if it is all that smart guys in comments are wrong about duplicate.
Andrey
What difference is there between a "has a" private inheritance and aggregation then ?
Cedric H.
+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
@Cedric With aggregation you can use several objects, like "has many", but with private inheritance you are locked to just one.
Zitrax
@Cedric: private inheritance allows you to override virtual functions and access protected members of the base class.
Mike Seymour
@David True I updated and changed "is a" to "implemented in terms of".
Zitrax
@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