#include<iostream>
using namespace std;
class Base{
private:
int a;
protected:
Base(){};
virtual ~Base(){};
};
class Derived:private Base{
private:
int b;
public:
Derived(){};
~Derived(){};
void test(){
Base world;
};
};
int main(){
}
inherit.cc|7 col 3| error: ‘Base::Base()’ is protected
inherit.cc|17 col 9| error: within this context
inherit.cc|8 col 11| error: ‘virtual Base::~Base()’ is protected
inherit.cc|17 col 9| error: within this context
But why?
And why this is correct?
#include<iostream>
using namespace std;
class Base{
private:
int a;
protected:
Base(){};
virtual ~Base(){};
void test2(){};
};
class Derived:private Base{
private:
int b;
public:
Derived(){};
~Derived(){};
void test(){
test2();
};
};
int main(){
}
In the first example you create an object of
Basein methodtest()ofDerivedclass.In second example you access the method
test2()which isprotectedinBase&Derivedderives from itprivately.Note the rule for access specifiers of a class:
In case of
privateInheritance:In example 1,
Eventhough,
Derivedderives fromBase, it can have access to protected members ofBaseonly for theBaseof theDerivedobject whose member function(test()) is being called not any otherBaseclass object.Given that you cannot create a
Baseobject.In example 2,
test2()is called on the object whose member function(test()) is being called, As noted aboveDerivedclass has access toprotectedmembers ofBasefor theBaseof theDerivedobject whose member function is being called and hencetest2()can be called.Good Read:
What are access specifiers? Should I inherit with private, protected or public?