The problem with protected fields in a base class in C ++

I have a base class, say BassClass , with some fields that I made them protected, and some pure virtual functions. Then the derived class, say DerivedClass , as the class DerivedClass : public BassClass . Should DerivedClass inherit protected fields from BassClass? When I tried to compile DerivedClass, the compiler complains that DerivedClass does not have any of these fields, what is wrong here? thanks

+4
source share
2 answers

If BassClass (sic) and DerivedClass are templates, and the BassClass member that you want to access from DerivedClass is not specified as a dependent name, it will not be visible.

eg.

 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 access, you need to provide additional information. For example, you can specify the full name of the participant:

  int get_value() {return BaseClass<T>::value;} 

Or you can make it explicit that you are referring to a class member:

  int get_value() {return this->value;} 
+8
source

It works:

 #include <iostream> struct Base { virtual void print () const = 0; protected: int val; }; struct Derived : Base { void print () { std::cout << "Bases val: " << val << std::endl; } }; 
0
source

All Articles