How to use ‘this' Pointer to Access Template Base Class Members In C++
To resolve the issue of dependent names, we can use the this
pointer in the derived class to make sure that the name should be looked up in the context of the base class only. The this
pointer is a pointer to the current instance of the class, so using it we can guide the compiler about where to look for the name.
C++ Program to Access Template Base Class Members through ‘this’ Pointer
The below example demonstrates the use of the ‘this’ pointer to access base class members in a class template.
// C++ program to access template base class members through
// the '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 through 'this'
// pointer
this->display();
}
};
int main()
{
Derived<int> obj1;
// calling a function of the derived class
obj1.display2();
return 0;
}
Output
Hello Geeks
Time Complexity: O(1)
Auxiliary Space: O(1)
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++.