this pointer in C++ | Tutorial & Example

What is this pointer ?

this pointer is pointer that is accessible only inside the member functions of a class and points to the object who has called this member function.
Let’s understand by an example,

Rise of this pointer : Behind the scene

Let’s understand this pointer in a step by step example,

Create a class Sample that contains a member variable m_value and one function display() that prints the value of m_value.

class Sample
{
	int m_value;
public:
	Sample()
	{
		m_value = 10;
	}
	void display()
	{
		std::cout<< m_value<<  std::endl;
	}
};

Now Let’s create an object of this class display() member function

	Sample obj;
	obj.display();

Inside this display function are printing m_value. But what happens behind the scenes ??

Whenever a member function is called through an object, compiler secretly pass the pointer of calling object to this member function i.e.

Compiler will secretly convert statement,

obj.display()

to,

obj.display(&obj);

Also, inside every member function compiler secretly pass the first parameter as the address of calling object i.e.

void Sample::display();

will be converted secretly to,

void Sample::display(Sample * this);

So, this is how this pointer comes in to picture. this pointer is secretly passed to each member function by the compiler. Also, when we access any member variable in member function, compiler uses this secretly passed this pointer to access that member variable.

[showads ad=inside_post]

 

So, display() function will be secretly changed by the compiler behind the scenes as follows,

void Sample::display(Sample * this)
{
    std::cout<<this->m_value<<std::endl;
}

Therefore, this pointer is accessible only inside member functions and points the address of the object with whom this member function is called.

Complete Executable code is as follows,

#include <iostream>

class Sample
{
	int m_value;
public:
	Sample()
	{
		m_value = 10;
	}
	void display()
	{
		std::cout<< m_value<<  std::endl;

		// Using this pointer
		std::cout<<  this->m_value  <<std::endl;
	}
};
int main()
{
	Sample obj;
	obj.display();
	return 0;
}

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top