This Pointer in C++

Advertisements

C++ This Pointer

C++ provides a keyword 'this', which represents the current object and passed as a hidden argument to all member functions.

The this pointer is a constant pointer that holds the memory address of the current object. The this pointer is not available in static member functions as static member functions can be called without any object. static member functions can be called with class name.

Example of this pointer


	#include<iostream.h>
	#include<conio.h>
	#include<string.h>

	class Student
	{

		int Roll;
		char Name[25];
		float Marks;

		public:

		Student(int R,float Mks,char Nm[])           //Constructor 1
		{
			Roll = R;
			strcpy(Name,Nm);
			Marks = Mks;
		}

		Student(char Name[],float Marks,int Roll)      //Constructor 2
		{
			Roll = Roll;
			strcpy(Name,Name);
			Marks = Marks;
		}

		Student(int Roll,char Name[],float Marks)       //Constructor 3
		{
			this->Roll = Roll;
			strcpy(this->Name,Name);
			this->Marks = Marks;
		}

		void Display()
		{
			cout<<"\n\tRoll : "<<Roll;
			cout<<"\n\tName : "<<Name;
			cout<<"\n\tMarks : "<<Marks;
		}
	};


	void main()
	{

		Student S1(1,89.63,"Sumit");
		Student S2("Kumar",78.53,2);
		Student S3(3,"Gaurav",68.94);

		cout<<"\n\n\tDetails of Student 1 : ";
		S1.Display();

		cout<<"\n\n\tDetails of Student 2 : ";
		S2.Display();

		cout<<"\n\n\tDetails of Student 3 : ";
		S3.Display();

	}


	Output :

	Details of Student 1 :
	Roll : 1
	Name : Sumit
	Marks : 89.63

	Details of Student 2 :
	Roll : 31883
	Name : ?&;6#?#?6#N$?%_5$?
	Marks : 1.07643e+24

	Details of Student 3 :
	Roll : 3
	Name : Gaurav
	Marks : 68.94

In constructor 1,variables declared in argument list different from variables declared as class data members. When compiler doesn't find Roll, Name, Marks as local variable, then, it will find Roll, Name, Marks in class scope and assign values to them.

But Constructor 2 will not initialize class data members. When we pass values to constructor 2, it will initialize values to itself local variables b'coz variables declared in argument list and variable declared as data members are of same name.

In this situation, we use 'this' pointer to differentiate local variable and class data members as shown in constructor 3.

Advertisement