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

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

Sceranio-1: Internal use of this pointer.

Wherever an object calls a class member function then compiler internally pass a THIS pointer to member function internally. For example, in below class, we have a Set model member function that receives one argument i.e. car model.

In fact, besides model parameter one more argument is passed to the set model function internally that is 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;
}

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

Scenario-2: Make class member fields and member function parameter readable.

One advantage of this pointer in C++ program is to make constructor or function parameter and class data member readable. In below class, member variable “ modle” and parameter “modle” in function SetModel(int model) are of same name. So, to make these items readable and unambiguous to program, we use this pointer. Example below.

Note that even though if we write model=model in SetModel function instead of this->model = model; the compiler will throw no error and everything would seem fine, but when you run the program, you’ll get garbage value. – this is another important point of using this before a member variable.

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



3 thoughts on “What is Advantage and Use of THIS pointer in C++ – Scenarios?”

  1. in scenario 2, if we assign model = model then the value is not assigned to data member so the actual usage is this->model = model which will assign the value correctly

    Reply
    • You’re right Chandrasekhar, we get garbage value at run time. Probably I added that note for no compiler error. Anyway sorry for my mistake. I’ve updated the post for run time error as you pointed- Thank you very much.

      Reply
  2. most typical use is cast consteness away in const methods – often to avoid duplicate code, e.g :

    class A {
    ….
    T& get() {
    // some complex retrieval code
    }

    T& get() const {
    // reuse non-const get
    return (const_cast(this))->get()
    }

    Reply

Leave a Comment