What is Advantage and Use of THIS pointer in C++ – Scenarios?

Answer includes uses and advantage of the this pointer in C++ programming with multiple scenarios where the this pointer is used.

Sceranio-1: Internal use of this pointer as an argument to a function.

Wherever an object calls a class member function, then the compiler internally passes a “this” pointer to the member function internally.

For example,

In the below class Car, we have a “SetModel” member function that receives one argument i.e. car model.

In fact, besides the model parameter, one more argument is passed to the set model function internally, and that is the “this” pointer.

class Car{
	int model;
public:
	void SetModel(int model){		
		this->model = model;
	}
};

int main(){

	int modelNumber = 1024;
	Car obj;
	//On calling function using class obj
	//THIS pointer is also passed internally besides
	//model number paramer.
	obj.SetModel(modelNumber);

	return 0;
}

You can Read in detail: “this” pointer internal working in C++.

Scenario-2: Use “this” pointer to assign value of the function’s parameter to a class member variable correctly

In the below code example,

the class member variable “ modle”, and the parameter “modle” in the function SetModel(int model) are of the same name.

class Car{
	int model;
public:
	void SetModel(int model){		
		this->model = model;
	}
};

Even though if we write model=model in the SetModel function instead of this->model = model; the compiler will throw no error and everything would seems fine at the compile time, but when you run the program, you’ll get garbage value.

Scenario-3: In a large code base of a function, identifying the class member variable is easy

Assume a function of a class or multiple functions uses the class fields and they have very large and complex code base, then

it’s easy for a programmer to identify the class fields. Specially when a maintenance or modification is done within it.

class Car{
	int model;
public:
	void SetModel(int m){
		// do something;


		this->model = m;
	}
};

Related Posts