#include <iostream>
using namespace std;
class Base
{
public:
Base(){cout <<"Base"<<endl;}
virtual ~Base(){cout<<"~Base"<<endl;}
virtual void foo(){ cout<<"foo base"<<endl;}
};
class Derived: private Base
{
public:
Derived(){cout<<"Derived"<<endl;}
virtual ~Derived(){cout<<"~Derived"<<endl;}
virtual void foo(){ cout<<"foo dervied"<<endl;}
};
int main(int argc, char *argv[])
{
Base *pb = new Derived;
Derived d;
d.foo();
return 0;
}
when I execute the above sample program I get following error: protected.cpp: In function ‘int main(int, char**)’: protected.cpp:26: error: ‘Base’ is an inaccessible base of ‘Derived’
Why its not possible to create Derived object with base pointer????
So I can create an instanse of Derived class like
Derived d
Derived d1= new Derived;
But creating instance from Base class pointer like
Base * b = new derived
will fail.
This is because Derived is not actaully a derived class from Base when derived procted and privately??
Is this correct?????
A protected member is accessible within its class and by derived class instances. For a comparison of protected with the other access modifiers, see Accessibility Levels. A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type.
Direct privately derived classes that also have private access to protected members. When preceding the name of a base class, the protected keyword specifies that the public and protected members of the base class are protected members of its derived classes.
When a class uses public member access specifier to derive from a base, all public members of the base class are accessible as public members of the derived class and all protected members of the base class are accessible as protected members of the derived class (private members of the base are never accessible unless friended)
2) I noticed that the private members of the base class will never be touched by the derived class. So why are the private members inherited? Because they are part of the base class, and you need the base class which is a part of your derived class.
Why its not possible to create Derived object with base pointer????
Because the base is private
. This explicitly forbids treating your class as a Base
instance from the outside. Seen from the outside, your class Derived
is not a subclass of Base
, only from inside the class itself.
The same counts for protected
inheritance, with the only difference that the base class now isn't private to the own class any more but rather to any derived class as well. To the outside though, it behaves just like private inheritance.
You might want to take a look at this faq on c++ and inheritance. Sections 24.5 and 24.6 in particular.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With