protected inheritance

Hi Guys,

I am confused as to why the code below does not work when I do new.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

class base { 

      public:
         base() { } 
} ; 

class derived : protected base { 

       public:
          derived() { } 
} ; 

int main() { 

       base *p = new derived() ; // why this does not work? 
       derived Obj             ; // and why this works ? 

       return 0 ; 
} 
closed account (S6k9GNh0)
EDIT: Don't mind me...
Last edited on
closed account (1yR4jE8b)
What? of course you can assign a derived class to a base pointer, that's the whole basis for polymorphism.

In fact, you can't do as you said computerquip. Think about it for a second, you would have an imcomplete derived object, so any attempt at invoking a function from the derived class would probably segfault the program. Visual Studio 2010 and g++ both give compile errors when you try to do that assignment.

The problem is that because of protected inheritance, the default constructor is not accessible. Although, I don't understand why this is be an issue considering that protected members are supposed to be accessible by derived classes. I'll admit, however, I'm not too familar with inheritance other than Public inheritance because I've never needed to use any kind of inheritance other than Public. Why do you want your class to have protected inheritance?
Thanks for the reply guys.

@computerquip: As darkestfright mentioned, we can have a base class pointer point to derived's object.

@darkestfright: Actually what I don't understand is, why would they not allow object to made dynamically when we can make it statically. I mean if we cannot make object using protected inheritance then what's the use of it? I understand that default constructor of base will be protected in derived class but then I shouldn't be able to make derived Obj too right?


Edit: typo
Last edited on
closed account (1yR4jE8b)
Yes when I attempted to fiddle with your code, I did find that it was ok to declare it statically. It is also ok, to dynamically allocate a derived object using a derived*, so I'm at a loss as to why a base* is preventing derived from accessing base's default constructor, but like I said, I have no experience with non-public inheritance.
You can do base *p = new derived() only with public inheritance ( derived: public base means derived is a base )
private and protected inheritance work differently:
http://www.parashift.com/c++-faq-lite/private-inheritance.html
closed account (1yR4jE8b)
Ok, I understand.

Private/Protected inheritance gives a "has-a" relationship instead of an "is-a" from Public inheritance. That's why you can't hold a reference to a derived with a base pointer. base is treated as a member of derived instead of as a part of base.
Last edited on
Thanks a lot for explanation guys.
Topic archived. No new replies allowed.