I have a base class, say BassClass
, with some fields, which I made them protected, and some pure virtual functions. Then the derived class, say DerivedClass
, like class DerivedClass : public BassClass
. Shouldn't DerivedClass inherit the protected fields from BassClass? When I tried to compile the DerivedClass, the compiler complains that DerivedClass does NOT have any of those fields, what is wrong here?
thanks
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.
12.4 Q4: When should base class members be declared protected? When all clients should be able to access these members. The protected access specified should never be used.
If a class is derived privately from a base class, all protected base class members become private members of the derived class. Class A contains one protected data member, an integer i . Because B derives from A , the members of B have access to the protected member of A .
No, we cannot declare a top-level class as private or protected.
If BassClass
(sic) and DerivedClass
are templates, and the BassClass
member you want to access from DerivedClass
isn't specified as a dependent name, it will not be visible.
E.g.
template <typename T> class BaseClass {
protected:
int value;
};
template <typename T> class DerivedClass : public BaseClass<T> {
public:
int get_value() {return value;} // ERROR: value is not a dependent name
};
To gain access you need to give more information. For example, you might fully specify the member's name:
int get_value() {return BaseClass<T>::value;}
Or you might make it explicit that you're referring to a class member:
int get_value() {return this->value;}
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