Accessing Protected Variables in Base Class objects from Derived Class Objects

Hi. I think the answer to this may be “because that’s the way it is”. But, here goes.

My base class has a “protected” member variable. I then derive a class from the base class.

It looks to me like:

  • Objects of the derived class can access their own copy of the protected member variable (defined in the base class). – Expected

  • Objects of the derived class can access the protected member variable belonging to other objects of the derived class. – Expected

  • Objects of the derived class cannot access the protected member variable belonging to objects of the base class. – Somewhat unexpected

This is illustrated in the simple code below. It won’t compile unless the last function in the derived class is commented out.

So, am I right? Is that just the way it is and there’s no way to do what the last function is attempting to do?

Thanks.

class BaseClass {
  protected:
    uint8_t protectedMember = 0;
};

class DerivedClass : public BaseClass {
  public:
    void setProtectedMember(uint8_t i) {
      protectedMember = i;
    }

    void setProtectedMember(DerivedClass &d, uint8_t i) {
      d.protectedMember = i;
    }

    // ********* The code will only compile if this function is commented out **********
    void setProtectedMember(BaseClass &b, uint8_t i) {
      b.protectedMember = i;
    }
};

void setup() {
}

void loop() {
}

When a class inherits another one, the members of the derived class can access the protected members inherited from the base class, but not its private members

A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class.

if you declare your base class this way, then it will compile:

class BaseClass {
    friend class DerivedClass; // probably not a great practice in this example
  protected:
    uint8_t protectedMember = 0;
};

Friendship and inheritance - vast topic

The issue is not accessing the private members, but protected ones.

It turns out that I can access a protected something that belongs to my “father”. And, I can access a protected something that belongs to my “uncle”, but only through my “cousin”. I can’t get to it directly by asking my “uncle”.

Of course, specifying a friend class would do the job. But, in this specific case, the base class is an established library that I’m adding a subclass to. So, ideally, I could do what I want without making a custom version of it just for this application.

Anyway, my idea was just an optimization and I can work without the base class access that I was looking for.

OK - yes, as commented above that’s somewhat a ugly practice to work around the way the language allows or block access when you are not “inside” your own instance.