1
#include<iostream>
#include<cstdio>
#include<vector>

#define MAX_SIZE 100
using namespace std;

template<class T>
class Base{
public:
    int top = 0;
};

template<class T>
class Derived: public Base<T>{
public:
    bool doo(void);
};

template<class T>
bool Derived<T>::doo(){
    top++;
    return true;
}


int main(int argc, char* argv[]){
    Derived<int> *obj = new Derived<int>;
    obj->doo();
    return(EXIT_SUCCESS);
}

Here I am inheriting the class Base in Derived class. When I call the function doo with an object of the Derived class(obj) I am not able to access the variable 'top' which is initialised in the Base class.

The error I get with the clang compiler is :

error: use of undeclared identifier 'top'
    top++;
    ^
1 error generated.

I tried a lot of things but I am not able to resolve this simple issue. From my understanding a derived class inherits all its base class members with the specified access specifiers, but when I apply this concept here it is not working. Please help me resolve it.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • 2
    You are confusing two related issues. The derived class does inherit the base class members, this is true. But the issue you are having is that the compiler in this context is not able to resolve the name `top` to the base class member also called `top`. The problem here is the template, as already explained below a simple fix is to write `this->top. – john Mar 29 '23 at 06:46
  • 2
    The process by which names in template code are resolved is called *two phase lookup*, a reasonably detailed explanation of this and alternative approaches can be found [here](https://devblogs.microsoft.com/cppblog/two-phase-name-lookup-support-comes-to-msvc/) – john Mar 29 '23 at 06:54

0 Answers0