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 ;
}
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?
@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?
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.
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.