The Problem in Accessing Template Base Class Members Without this Pointer
When a template class derives from another template class, the base class’s members are considered dependent on the template parameters and are unknown to the compiler until the template is instantiated. This creates a problem where the derived class template does not automatically consider the base class scope when compiling the template. As a result, if we try to use a base class member directly in the derived class without qualification, the compiler can’t do anything meaningful to fix it in the first stage of compilation.
In the following program, we try to access the template base class members without this pointer to see what are the consequences:
// C++ program to access template base class members without
// 'this' pointer
#include <iostream>
using namespace std;
template <typename T> class Base {
public:
void display() { cout << "Hello Geeks" << endl; }
};
template <typename T> class Derived : public Base<T> {
public:
void display2()
{
// Accessing base class member without 'this'
// pointer
display();
}
};
int main()
{
Derived<int> obj1;
// calling a function of the derived class
obj1.display2();
return 0;
}
Output
error: there are no arguments to 'display' that depend on a template parameter, so a declaration of 'display'
must be available [-fpermissive]
Why Do I Have to Access Template Base Class Members Through the ‘this’ Pointer?
In C++, when we have a class template that inherits from a template base class, we need to explicitly use this pointer to access members of the base class. In this article, we will learn why it is necessary to access template base class members through ‘this’ pointer in C++.