After years of programming in C, I'm doing my first steps in C++.
I'm trying to grasp the "protected" concept, and there is a lot of material on the web that explains what a protected variable is, and what they are used for. However, when trying to code a super-basic example, just to get my hands dirty with C++, I bumped into an error:
error: 'int parent::protected1' is protected within this context
So, a little help will be appreciated.
class parent {
public:
int getProtected() { return protected1; }
protected:
int protected1;
};
class child: public parent { };
int main()
{
child ch;
cout << ch.protected1 << endl; // error: 'int parent::protected1' is protected within this context
cout << ch.getProtected() << endl; // OK
return 0;
}
Everywhere it is said that protected variables are only accessible within an inheritance hierarchy. If that's the case, I'm trying to understand - what am I doing wrong here?
The concept of "protected variable" hasn't really sunk in. The private is well understood, as a private variable belongs to the child instance and therefore can be accessed only by child methods. However, if a child can access a protected variable of the parent, does it mean a parent must be instantiated before a child can access this protected variable?