×

C++ this Pointer




this pointer

If we want an address of an object within same class then this pointer is used. It is used as self reference within a class.

#include <iostream>
class Student 
{
int rollNo;
char name[20];
public:
    Student (int rollNo, char name[])
    {
     this -> rollNo = rollNo;
     strcpy(this -> name , name);
    }

     void showInfo()
     {
       cout<<"Roll No is " <// Function returning address of object 
     Student *getAddress()
     {
       return this;
     }

Function returning object     
Student getObject()
{
return *this;
}
}; 

void main()
{
Student a(64,"Manish");
Student *p = a.getAddress();
Student b = a.getObject();
}