Using an undeclared identifier in C ++ with patterns and inheritance

The following code cannot compile - using an undeclared identifier. I use GCC and Xcode to compile.

Everything is in one 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 the compile error. addStuff is not declared. } 

Does anyone have an explanation? Thanks in advance!

+7
source share
4 answers

to try

 this->addStuff(thingy); 
+14
source

There are several problems:

  • Missing semicolons after class definitions.
  • There is no type to declare / define the doSomething method.
  • Missing addStuff method definition type.

After fixing what seems to work .

Edit: How you fixed syntax errors and it still doesn't work. Like others, your compiler may require that you addStuff method with the prefix this-> :

 this->addStuff(thingy); 
+5
source

This is due to template inheritance. In this case, you should mannualy specify the usage for the base methods:

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

or do it with this pointer:

 template <typename T> MyDerived<T>::doSomething() { T* thingy = new T(); this->addStuff(thingy); } 
+2
source

use this pointer to call the addStuff ie method

 this->addStuff(thingy); 
+1
source

All Articles