Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: is "this" pointer useless?

in the code below, it does not matter whether i put "this->" or remove it. it gives same output and result in both cases. So, what is the point of having the "this" pointer in C++? Are there other usages where it is essential? Thanks.

#include<iostream>
using namespace std;

class square{
    int l;
    int w;
    public:
        square(int x, int y){
            w = x;
            l = y;
        }
        int getArea(){
            return w * l;
        };
        bool AreaSmallerThan(square c){
            if(this->getArea() < c.getArea())
                return true;
            else
                return false;
        }

};

int main(){
    square A(2,3);
    square B(1,3);
    if(A.AreaSmallerThan(B))
        cout<<"A is smaller than B."<<endl;
    else
        cout<<"A is NOT smaller than B."<<endl;
    return 0;
}
like image 813
CSawy Avatar asked Sep 13 '26 06:09

CSawy


1 Answers

TL;DR: It has it's uses. If you choose good naming practices, you generally won't need to use it often.

There are a number of cases where you would want a "pointer to the current object", for example:

struct Foo
{
    void MakeCallback(eventid_t eventId)
    {
        scheduleCallback(eventId, callbackProxyFn, this);
    }

    static void callbackProxyFn(eventid_t eventId, Foo* foo)
    {
        // call 'callback' on the relevant object instance.
        foo->callback(eventId);
    }

    void callback(eventid_t eventId);
};

It can also be used to resolve conflicts between names in the current object and other scopes, if you choose to use terrible naming conventions.

void Foo::bar(int n)
{
    this->n = n;
}

You could avoid this (pun intended) scenario, as is common practice, by prefixing statics, globals and members:

class Player {
    int m_score;
public:
    Player(int score) : m_score(score) {}
};

Player g_player1;
static Player s_login; // yeah, I know, terrible, just an example tho.

A common use is in eliminating self in copy/comparison operators:

bool Foo::operator==(const Foo& rhs) const
{
    if (this == &rhs)
         return true;
    ...
}

You can also use it to produce a reference to the current object:

foo(const Foo&);

void foo(*this);
like image 121
kfsone Avatar answered Sep 15 '26 03:09

kfsone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!