CPP Tutorial

CPP examples programs

CPP this Pointer

In CPP library, this is a pre-defined keyword which is used to refer to the current instance of a class.

Usage of CPP this Pointer:

  • to pass current object as a parameter to another method.
  • to refer current class instance variable.
  • to declare indexers.

Example:

#include <iostream.h>
using namespace std;
 
class Student
{
public:  
string Name;  
float ID;
Student(string Name, float ID) 	 
{    
this-> Name = Name;    
this-> ID = ID;   
}    
void details()
{
cout << "Student Name : " << Name << endl;
cout << "Student ID: " << ID << "\n\n";
}
};
int main()
{
Student s1 = Student("Khush", 1);    
Student s2 = Student("Raam", 2);  
s1.details();    
s2.details();    
return 0;
}

Output

Student Name : Khush                
Student ID: 1   
 
Student Name : Raam 
Student ID: 2