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
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.
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
.