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
Asked
Active
Viewed 4,910 times
6

derrdji
- 12,661
- 21
- 68
- 78
-
4yeah what you describe sounds like it should work. This probably boils down to how your code is written. Give us a basic example that recreates your compiler error, then we can help you. – Doug T. Nov 28 '09 at 20:22
-
Are you inheriting from a templated class? If so, you need to use this-> when accessing member variables from the base class. – Charles Salvia Nov 28 '09 at 20:32
-
1What do you mean "inherit the protected fields"? Any subclass always has all fields of its base classes, whether they're public, protected or private. The question is who can access them - if the member is protected, that means only code inside DerivedClass can access the member, and code outside DerivedClass looking at an object of type DerivedClass cannot access it. – Steve Jessop Nov 28 '09 at 20:40
2 Answers
11
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;}
-
5The reason for this template behaviour, by the way, is that at the point where the DerivedClass template is defined, the compiler has no way of knowing whether `BaseClass
` is going to have a member `value` or not. You might late specialise `BaseClass – Steve Jessop Nov 28 '09 at 20:44` so that it doesn't have one, and then try to instantiate `DerivedClass `. So the template definition is supposed to be rejected. By adding the extra information you're saying "it's OK, what `value` is depends on `T`, so don't expect to be able to find it yet". -
2Alternatively, we can do `using BaseClass
::value;` in the derived class declaration, which would allow the rest of the derived class to simply call `value`. – int3 Nov 28 '09 at 21:10
0
This works:
#include <iostream>
struct Base {
virtual void print () const = 0;
protected:
int val;
};
struct Derived : Base {
void print () { std::cout << "Bases's val: " << val << std::endl; }
};

rmn
- 2,386
- 1
- 14
- 21