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?
Protected members in a class are similar to private members as they cannot be accessed from outside the class. But they can be accessed by derived classes or child classes while private members cannot.
Protected Access Modifier - Protected Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class. The protected access modifier cannot be applied to class and interfaces.
The protected members are inherited by the child classes and can access them as its own members. But we can't access these members using the reference of the parent class. We can access protected members only by using child class reference.
The protected access modifier is accessible within the package. However, it can also accessible outside the package but through inheritance only. We can't assign protected to outer class and interface. If you make any constructor protected, you cannot create the instance of that class from outside the package.
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
.
It is accessible within the scope of B's functions, but you are attempting to access it in main.
But you're not accessing it from the derived class. You're accessing it from main().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With