I have written a template base class as below:
template<typename T>
class Base {
public:
Base(T x);
void print_base();
virtual ~Base();
protected:
T data;
};
template<typename T>
Base<T>::Base(T x) : data(x) {}
template<typename T>
void Base<T>::print_base()
{
std::cout << data << std::endl;
}
template<typename T>
Base<T>::~Base() {}
Now, I am trying to write a derived class as the below:
template<typename T>
class Derived : public Base<T>
{
public:
Derived(T x);
void print_derived();
private:
};
template<typename T>
Derived<T>::Derived(T x) : this->Base(x) {}
template<typename T>
void Derived<T>::print_derived()
{
this->print_base();
std::cout << " data " << this->data << std::endl;
}
But the compiler reports error on the below line:
template<typename T>
Derived<T>::Derived(T x) : this->Base(x) {}
The error is as below:
template_derived_class_this.h:12:28: error: expected identifier before 'this'
Derived<T>::Derived(T x) : this->Base(x) {}
If I change it to the below the error goes away:
Derived<T>::Derived(T x) : Base<T>::Base(x) {}
My question is what is the reason for the error in the this-> prefix format? Is it because before the constructor has finished running the this pointer is not yet ready or am I making any syntactical error here? I have seen this-> being used inside the constructor elsewhere. So not sure what is the reason for the error in my case. I am compiling with the below command:
g++ template_inheritance_main_this.cpp -o template_inheritance_main_this -Wall
-Wextra -Wpedantic -Werror