1
template <class T>class Array { protected : T* data; int size; }; template<class T>class Stack : protected Array<T> { int top; public: Stack(){}; public: void Push(T x) {data[++top] = x;} }; 

Why it say '"data" was not declared in this scope' in Push? How can I fix this? When I delete each template<T>, it works normally. Is something wrong in my template?

2 Answers 2

7

You need:

template <class T>class Array { protected : T* data; int size; }; template<class T>class Stack : protected Array<T> { int top; public: Stack(){}; public: // void Push(T x) {data[++top] = x;} <-- Won't compile void Push(T x) {this->data[++top] = x;} // <-- Will compile // void Push(T x) {Array<T>::data[++top] = x;} <-- Will also compile }; 

Because within the implementation of a class template derived from a class template, members of the base template must be referred to via the this pointer or with base-class qualification.

Sign up to request clarification or add additional context in comments.

Comments

2

As an addition to @Mike's answer you might consider using using declaration:

template <class T>class Array { protected : T* data; int size; }; template<class T>class Stack : protected Array<T> { using Array<T>::data; // <--- HERE int top; public: Stack(){}; public: void Push(T x) {data[++top] = x;} }; 

Now data becomes available in Stack class.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.