I thought that protected members of a Base class can be accessed by instances of the Derived class (or any classes that derive from the Derived class, given that they inherit from the latter publicly).
But I get an error when attempting to do just that in the following listings. So what am I missing?
class Base{
private:
virtual void f(){cout << "f of Base" << endl;}
public:
virtual ~Base(){}
virtual void g(){this->f();}
virtual void h(){cout << "h of Base "; this->f();}
};
class Derived: protected Base{
public:
virtual ~Derived(){}
virtual void f(){cout << "f of Derived" << endl;}
private:
virtual void h(){cout << "h of Derived "; this->f();}
};
int main(){
Base *base = new Base();
cout << "Base" << endl;
base->g(); //f of Base
base->h(); //h of Base f of Base
Derived *derived = new Derived();
cout << "Derived" << endl;
derived->f(); //f of Derived
derived->g(); //this doesn't compile and I get the error "void Base::g() is inaccessible within this context". Why?
derived->h(); //this doesn't compile given that h is private in Derived
delete base;
delete derived;
return EXIT_SUCCESS;
}