0

I am trying to access data of the superclass within the subclass, but i need to do this by passing a different pointer (i.e. not using *this) into the function. The test code would look like the following:

class Superclass
{
protected:
        int data;
};

class Subclass : public Superclass
{
public:
        void foo(Superclass *p)
        {
                p->data = 5;
        }
};

int main()
{
        Superclass sup;
        Subclass sub;

        sub.foo(&sup);

        return 0;
}

I would expect it to work, but this produces an error:

error: ‘int Superclass::data’ is protected within this context

Why is this protected, when i should be able to see the data of the superclass?

v010dya
  • 5,296
  • 7
  • 28
  • 48
  • 1) `->` is for pointers, but you're using it for a non-pointer in your main. 2) `protected` acts like `private` --- you cannot access `protected` members unless they're members of the inheriting class. – erip Aug 28 '22 at 12:17
  • it's `sub.foo(&sup);` not `sub->foo(&sup);` . also to access the protected member simply write `data = 5;` not `p->data = 5;` and no need for that parameter to that function – abdo Salm Aug 28 '22 at 12:22

0 Answers0