Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with protected fields in base class in c++

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

like image 657
derrdji Avatar asked Nov 28 '09 20:11

derrdji


People also ask

Can base class access protected members of derived class?

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.

When should you declare base class members protected?

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.

How are protected members of a base class in C++?

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 .

Can we declare public/private protected in base class?

No, we cannot declare a top-level class as private or protected.


1 Answers

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;}
like image 115
Managu Avatar answered Sep 23 '22 06:09

Managu