0

I get the compiler error "Use of undeclared identifier '_storage'"

#include <iostream>

struct Storage{
    int t;
};

struct DerivedStorage : Storage{
    int s;
};

struct DerivedStorage2 : DerivedStorage{
    int r;
};

template<typename DS = Storage>
class Base{
public:
    DS* _storage = nullptr;
    Base(){
        _storage = new DS();
    }
    void m(){
        _storage->t++;
    }
};

template<typename DS = DerivedStorage>
class Derived : public Base<DS>{
public:
    void m2(){
        _storage->s++; //error here
    }
};

template<typename DS = DerivedStorage2>
class Derived2 : public Derived<DS>{
public:

    void m3(){
        _storage->r++; //error here
    }
};

int main(int argc, const char * argv[]) {
    Derived2<DerivedStorage2> t;
    for(int i = 0;i<3;i++){
        t.m3();
    }
    
    return 0;
}

Any idea what the problem is ?

Rahul Iyer
  • 19,924
  • 21
  • 96
  • 190

1 Answers1

2

Because Derived itself does not have a member variable named _storage, use this->_storage to access Base's _storage instead.

void m2(){
  this->_storage->s++;
}

Demo

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
  • 1
    https://stackoverflow.com/questions/993352/when-should-i-make-explicit-use-of-the-this-pointer This should be useful to explain why. – Rahul Iyer Mar 05 '22 at 05:11