I write a virtual function with protected inherientence
#include<iostream>
using namespace std;
class D{
private:
int a;
protected:
int b;
public:
D(){a=b=c=0;}
virtual void f(){
a=2;
cout <<"D::f"<<a<<endl;
}
void g(){cout<<"D::g"<<a<<endl;}
int c;
};
class E:protected D{
private:
int a,b,c;
public:
E(){a=b=c;}
void f(){
a=3;
cout<<"E::f"<<a<<endl;
}
void g(){cout<<"E::g"<<a<<endl;}
};
int main(){
D *d = new E;
d->f();
d->g();
return 0;
}
but if I use it, it turn out inaccessible base.
If I change it to public inherience , it can run.
I wonder that why I cannot use D *d = new E; with private and protected inherience?
Thx in advance.
privateorprotectedbase means the base is inaccessible to the world. So when you write an expression which requires conversion from the derived to the inaccessible base, that is forbidden due to accessibility rules because the conversion needs to take place at the call-site which is a part of the world.In object-oriented terminology,
privateorprotectedbase doesn’t define is-a relationship. It is actually an implemented-in-terms-of relationship, which is composition in simpler term.