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?
You are trying to access directly the class member protected1. This is possible only if the member is public.
Your class child can still access that member, so you could try:
class parent {
public:
    int getProtected() { return protected1; }
protected:
    int protected1;
};
class child: public parent { 
public:
  int getProtectedFromChild() { return protected1; }
};
int main()
{
    child ch;
    cout << ch.getProtected() << endl;   // OK
    cout << ch.getProtectedFromChild() << endl;   // This should work
    return 0;
}
A protected member variable can only be accessed via member functions of the parent or child class, as your example shows. Thus:
ch.protected1
does not compile since you are trying to access the data member from outside the class.
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