1

I tried c++ template class, but I find that I can't access val in class A, if I don't use template, it is ok to acccess it, even I can't use val in B's methold, I still can use it in main function, this behavia is really strange. does anybody know why?

#include <iostream>
#include <cstdio>
#include "name.h"
#include <map>
using namespace std;

template<class T>
class A {
    public:
        T val;
        A(T obj) {
            val = obj;
        }
        virtual void print() {
            cout << "in A" << endl;
        }
};

template<class T>
class B: public A<T> {
    public:
        B(T obj):A<T>(obj) {
        }
        void print() {
//if you unccomment this line, this program can't be compiled,
//            cout << val << endl;
            cout << "in B" << endl;
        }
};

int main() {
    string str = "`12";
    B<string> * b = new B<string>(str);
    A<string> * a = (A<string> *) b;
    b-> print();
    a-> print();
    cout << a-> val << endl;
//but it is ok to access val like this
    cout << b-> val << endl;
    return 0;
}
storm
  • 395
  • 1
  • 4
  • 11

1 Answers1

4

You need to reference it as this->val. This is because val is what is known as a non-dependent type.

You can alternatively utilize a using A<T>::val before hand, or refer to it with A<T>::val.

The C++ FAQ gives a (somewhat) detailed explanation of this.

Yuushi
  • 25,132
  • 7
  • 63
  • 81