C++ – Why can’t I access a protected member from an instance of a derived class

cinheritance

I haven't done C++ in a while and can't figure out why following doesn't work:

class A {
protected:
  int num;
};

class B : public A {
};

main () {
  B * bclass = new B ();
  bclass->num = 1;
}

Compiling this produces:

error C2248: 'A::num' : cannot access protected member declared in class 'A'

Shouldn't protected members be accessible by derived classes?

What am I missing?

Best Answer

yes protected members are accessible by derived classes but you are accessing it in the main() function, which is outside the hierarchy. If you declare a method in the class B and access num it will be fine.