1

might be a bit of a coward-ish question: I've got two classes, and declared all variables public. Why can't I access the variables from derived class??

g++ tells me: vec3d.h:76:3: error: ‘val’ was not declared in this scope

template<typename TYPE>
class vec{
public:
        TYPE *val;
        int dimension;
public:
        vec();
        vec( TYPE right );
        vec( TYPE right, int _dimension );

[etc]


template<typename TYPE>
class vec3d : public vec<TYPE>{
public:
        vec3d() : vec<TYPE>( 0, 3 ){};
        vec3d( TYPE right ) : vec<TYPE>( right, 3 ){};
        vec3d( TYPE X_val, TYPE Y_val, TYPE Z_val ) : vec<TYPE>( 0, 3 ){
                val[0] = X_val; //// <----------THIS ONE FAILS!
                val[1] = Y_val;
                val[2] = Z_val;
        };
[etc]
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
0815ZED
  • 123
  • 1
  • 12
  • 1
    can you remove all the comments in that code, it makes it really hard to read... – Tony The Lion Sep 02 '11 at 08:45
  • possible duplicate of [Access protected member of a class in a derived class](http://stackoverflow.com/questions/1624564/access-protected-member-of-a-class-in-a-derived-class) – CB Bailey Sep 02 '11 at 08:49
  • 1
    For future reference this question would have been easier to read if you'd reduced it to a 10 line example, without the full blown vector and '[etc]'. See [Short, Self Contained, Correct (Compilable), Example](http://sscce.org/). – Flexo Sep 02 '11 at 08:50
  • yeah now it's a bit more clear...i thought it got something to do with the public declaration...all tutorials do protected... as in the duplicate. Since this is not the issue I could've used the other thread - sorry guys ;) – 0815ZED Sep 02 '11 at 08:52
  • I removed the comments. They were mostly worthless anyway. – sbi Sep 02 '11 at 08:55

2 Answers2

5

This is purely a lookup issue and nothing to do with access control.

Because vec3d is a template and its base class depends on the template parameter, the members of the base class are not automatically visible in the derived class in expression that are non-dependent. The simplest fix is to use a dependent expression such as this->X_val to access members of the base class.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
3

You will need to refer to them via this->val or vec<TYPE>::val. There's a good explanation in this answer to a similar question.

Community
  • 1
  • 1
Flexo
  • 87,323
  • 22
  • 191
  • 272
  • Thanks...so they're not actual members of the new class although defined public?? – 0815ZED Sep 02 '11 at 08:45
  • They are still members, it's a name lookup issue. They need to be looked up later on than they would if they were left unqualified. – Flexo Sep 02 '11 at 08:48