Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of undeclared identifier in C++ with templates and inheritance [duplicate]

The following code cannot compile - use of undeclared identifier. I use GCC and XCode for compilation.

Everything is in a single header file.

include "MyArray.h"

template <typename T>
class MyBase {
public:
  MyBase();
  virtual ~MyBase();
  void addStuff(T* someStuff);
protected:
  MyArray<T*> stuff;
};

template <typename T>
MyBase<T>::MyBase() {}
template <typename T>
MyBase<T>::~MyBase() {}

template <typename T>
void MyBase<T>::addStuff(T* someStuff) {
  stuff.add(someStuff);
}

// ---------------------

template <typename T>
class MyDerived : public MyBase<T> {
public:
  MyDerived();
  virtual ~MyDerived();
  virtual void doSomething();
};

template <typename T>
MyDerived<T>::MyDerived() {}
template <typename T>
MyDerived<T>::~MyDerived() {}

template <typename T>
void MyDerived<T>::doSomething() {
  T* thingy = new T();
  addStuff(thingy); //here's the compile error. addStuff is not declared.
}

Does anyone have an explanation? Thanks in advance!

like image 516
user1414745 Avatar asked May 24 '12 10:05

user1414745


3 Answers

try

this->addStuff(thingy);
like image 139
juanchopanza Avatar answered Oct 20 '22 14:10

juanchopanza


It's due to template inheritance. In such case you should mannualy specify using for base methods:

template <typename T>
MyDerived<T>::doSomething() {
  using MyBase<T>::addStuff;
  T* thingy = new T();
  addStuff(thingy); 
}

or do it by this pointer:

template <typename T>
MyDerived<T>::doSomething() {
  T* thingy = new T();
  this->addStuff(thingy); 
}
like image 29
inkooboo Avatar answered Oct 20 '22 16:10

inkooboo


There are several issues:

  1. Missing semicolons after class definitions.
  2. Missing type for doSomething method declaration/definition.
  3. Missing type for definition of addStuff method.

After fixing that it seems to work.

Edit: As you have fixed the syntax errors and it still does not work. As others have suggested your compiler may require you to call the addStuff method with this-> prefix:

this->addStuff(thingy);
like image 6
Juraj Blaho Avatar answered Oct 20 '22 14:10

Juraj Blaho