Why can't I access a protected member from an instance of a derived class?
Solution 1:
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.
Solution 2:
Yes, protected members are accessible by the derived class, but only from within the class.
example:
#include <iostream>
class A {
protected:
int num;
};
class B : public A { public:
void printNum(){
std::cout << num << std::endl;
}
};
main () {
B * bclass = new B ();
bclass->printNum();
}
will print out the value of num
, but num
is accessed from within class B
. num
would have to be declared public to be able to access it as bclass->num
.
Solution 3:
It is accessible within the scope of B's functions, but you are attempting to access it in main.
Solution 4:
But you're not accessing it from the derived class. You're accessing it from main().