3

Visual studio is telling me I can't access a member variable from and instance of a parent class. Something like this:

class Parent { 
protected: 
      int x;
};

class Child : public Parent {
public:
    void foo(Parent* p) {
        p->x;
    }
};

I'm new to c++, is there something I'm doing wrong here?

Matt Capone
  • 147
  • 5
  • I’ve changed my mind: this isn’t a duplicate. True, the other question’s answers answer this question, but only incidentally. In addition, this question is much clearer and should be answered directly rather than be redirected. – Konrad Rudolph Oct 11 '13 at 23:03
  • 1
    That is wrong. If it's protected you cannot access the variable of `p`. But `Child` has a variable `x`, since it inherits it from `Parent`. Though it's impossible to access `p->x`. `p` has nothing to do with the `x` of `Child`. Was this helpful? `protected` members of a class `Parent` are not accessible outside of Parent's code, but are accessible from the code of any class derived from `Parent', in this case `Child`. Check this out: http://stackoverflow.com/questions/224966/private-and-protected-members-c – ipinak Oct 11 '13 at 23:08
  • You could declare Child as a friend of Parent. Just add friend class Child; to the definition of class Parent. This is okay if you are the maintainer of Parent and you know what all derived classes of Parent should really do with x (it is a design issue). – Tobias Oct 11 '13 at 23:33

0 Answers0