Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inheritance of template objects (G++ compiler)

#include <cstdlib>
#include <vector>
#include <iostream>

using namespace std;

class CFirstLevel {
 public:
    CFirstLevel (const string & _name): name (_name) {}
    // ...

 protected:

    string name;

};

template <typename T>
class CSecondLevel: public CFirstLevel {
 public:

    CSecondLevel (const string & _name): CFirstLevel (_name) {}

    virtual void PushBack (T) = 0;
    virtual void Print    (int I) {cout << data [I] << endl;}
    // ...

 protected:
    vector<T> data; 
};

template <typename A>
class CThirdLevel: public CSecondLevel<A> {
 public:
    CThirdLevel (const string & _name): CSecondLevel<A> (_name) {}

    virtual void PushBack (A _value) {data.push_back (_value);}

};


int main ( void ) {

    CThirdLevel<int> * pointer = new CThirdLevel<int> ("third");
    pointer -> PushBack (111);

    pointer -> Print (0);

    return 0;

}

Compiler return error:

main.cpp: In member function ‘virtual void CThirdLevel::PushBack(T)’:

main.cpp:32:37: error: ‘data’ was not declared in this scope

Where is a problem? Is it possible use this inheritance?

like image 277
Peter K. Avatar asked May 29 '13 14:05

Peter K.


2 Answers

The problem is in CThirdLevel. The field data cannot be resolved from CSecondLevel. You can solve this by changing

virtual void PushBack (A _value) {data.push_back (_value);}

to

virtual void PushBack (A _value) {CSecondLevel<A>::data.push_back (_value);}
like image 136
Marc Claesen Avatar answered Oct 02 '22 03:10

Marc Claesen


As Marc suggested, use

virtual void PushBack (A _value) { CSecondLevel<A>::data.push_back (_value); }

Alternatively, you could do

virtual void PushBack (A _value) { this->data.push_back (_value); }
like image 30
Steven Maitlall Avatar answered Oct 02 '22 04:10

Steven Maitlall