Open In App

Type of ‘this’ Pointer in C++

In C++, this pointer refers to the current object of the class and passes it as a parameter to another method. ‘this pointer‘ is passed as a hidden argument to all non-static member function calls. 

Type of ‘this’ pointer

The type of this depends upon function declaration. The type of this pointer is either const ExampleClass * or ExampleClass *. It depends on whether it lies inside a const or a non-const method of the class ExampleClass.

1) Const ExampleClass:

If the member function of class X is declared const, the type of this is const X* 

Example:




// C++ Program to demonstrate
// if the member function of a
// class X is declared const
#include <iostream>
using namespace std;
  
class X {
    void fun() const
    {
        // this is passed as hidden argument to fun().
        // Type of this is const X* const
    }
};

2) Non-Const ExampleClass

If the member function is declared volatile, the type of this is volatile X* as shown below

Example:




// C++ Program to demonstrate
// if the member function is
// declared volatile
#include <iostream>
using namespace std;
  
class X {
    void fun() volatile
    {
        // this is passed as hidden argument to fun().
        // Type of this is volatile X* const
    }
};

If the member function is declared const volatile, the type of this is const volatile X*.

Example:




// C++ program to demonstrate
// if the member function is
// declared const volatile
#include <iostream>
using namespace std;
  
class X {
    void fun() const volatile
    {
        // this is passed as hidden argument to fun().
        // Type of this is const volatile X* const
    }
};

Please note that const, volatile, and const volatile are type qualifiers.

What are type qualifiers?

A type qualifier is a keyword that is applied to a data type variable resulting in a qualified type.

For Example, float is the corresponding unqualified type, simply a floating number, while const float is a qualified type representing a constant floating number.

Note: ‘this’ pointer is not an lvalue.


Article Tags :
C++