Q:

Where we should use this pointer in C++?

0

Where we should use this pointer in C++?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

There are a lot of places where we should use this pointer. Below I am mentioning some scenarios where you should use this pointer, so let see.

1. When the local variable’s name is the same as the member’s name?

#include<iostream>
using namespace std;
class Test
{
private:
    //member variable
    int x;
public:
    void setX (int x) //x is local
    {
        // The 'this' pointer is used to retrieve the object's x
        // hidden by the local variable 'x'
        this->x = x;
    }
    void DisplayX()
    {
        cout << "x = " << x << endl;
    }
};
int main()
{
    Test obj;
    int x = 20;
    obj.setX(x);
    obj.DisplayX();
    return 0;
}

2. To return a reference to the calling object.

/* Reference to the calling object can be returned */
Test& Test::func ()
{
   // Some processing
    return *this;
}

3. When needs chain function calls on a single object.

#include<iostream>
using namespace std;
class Test
{
private:
    int x;
    int y;
public:
    Test(int x = 0, int y = 0)
    {
        this->x = x;
        this->y = y;
    }
    Test &setX(int a)
    {
        x = a;
        return *this;
    }
    Test &setY(int b)
    {
        y = b;
        return *this;
    }
    void print()
    {
        cout << "x = " << x << " y = " << y << endl;
    }
};
int main()
{
    Test obj(7, 7);
    obj.print();
    // Chained function calls. All calls modify the same object
    // as the same object is returned by reference
    obj.setX(10).setY(20).print();
    return 0;
}

Output:

x = 7 y = 7
x = 10 y = 20

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Interview Questions and Answers(2022)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
What is a “new” keyword in C++?... >>
<< What is “this” pointer in c++?...