I am trying to override functions in my program in the method below but when compiling it shows variable1 as undefined in the Derived clear function.
I have been able to get this to work when changing the derived class to a non-template, but then I am missing the DATATYPE and VALUE variables when initiating the template for Base.
template <class DATATYPE=short, short VALUE = 100>
class Base {
public:
Base();
virtual void clear()=0;
protected:
int variable1;
}
template <class DATATYPE=short, short VALUE = 100>
class Derived : public Base<DATATYPE, VALUE> {
public:
Derived();
void clear() {
int testVar = variable1;
}
}
CodePudding user response:
A compiling version of your code:
template <typename data_t, short value_v>
class Base
{
public:
Base() = default; // <== was missing impl, set to default
virtual ~Base() = default; // classes with virtual methods must have virtual destructor
virtual void clear() = 0;
protected:
int variable1;
};
template <typename data_t = short, short value_v = 100>
class Derived :
public Base<data_t, value_v>
{
// by adding a using you can more easily change the template params
// without having to update all your code. Helps keeping code more readable too
using base_t = Base<data_t, value_v>;
public:
void clear() override // <== missing override
{
// different ways of accessing member in template base class
int v1 = Base<data_t, value_v>::variable1;
int v2 = this->variable1;
int v3 = base_t::variable1;
}
};
int main()
{
Derived<short,100> d;
d.clear();
}