Ad

C++ this pointer

CPP uses a unique keyword called 'this', to represent an object that invokes a member function. 'this' is a pointer type object that points to the same class for which it was called. 'this' is a unique pointer that is automatically passed to a member function when it is called. 'this' pointer acts as an implicit argument to all the member functions.

Example 1: this pointer refers to the class variable

#include<stdio.h>
#include<conio.h>

class example
{
    int a, b;
    public:
    void input(int a, int b)
    {
        this->a = a; //instead of a=a
        this->b = b; //instead of b=b
    }
    void output()
    {
        cout<<"A = "<<a<<"\nB = "<<b;
    }
};
int main()
{
    int a, b;
    clrscr();
    cout<<"Enter 1st number: ";
    cin>>a;
    cout<<"Enter 2nd number: ";
    cin>>b;
    example ex;
    ex.input(a, b);
    ex.output();
    getch();
}
Enter 1st number: 50
Enter 2nd number: 100
A = 50
B = 100

Example 2: this pointer refers to the class object. Input 2 numbers and find greater.

#include<stdio.h>
#include<conio.h>

class example
{
    int a;
    public:
    void input(int x)
    {
        a = x;
    }
    example output(example ob)
    {
        if(a>ob.a)
            return *this;
        else
            return ob;
    }
    void display()
    {
        cout<<"Value = "<<a;
    }
};
int main()
{
    int a;
    clrscr();
    cout<<"Enter 1st number: ";
    cin>>a;
    object1.input(a);
    cout<<"Enter 2nd number: ";
    cin>>a;
    example object1, object2, object3;
    object2.input(a);
    object3 = object1.output(object2);
    object3.display();
    getch();
}

Exercise Question - 'this' pointer

  1. WAP to find sum of 2 number with the help of 'this' pointer. CPP

C Language Feedback, Questions, Suggestions, Discussion.