0

I wonder if there is some reason or not to use this in a attribute class?

class Foo
{
    private:
        int m_foo;

    public:
        int getIntance() { return this->m_foo; }
}

Other than the fact its say that this is the current class, are there others reasons?

3 Answers3

1

No, do not use it. In that particular case, it is not needed, and this is less typing :

int getIntance() { return m_foo; }

Less you write is better. Even for people reading you code (they'll have less to read)

BЈовић
  • 62,405
  • 41
  • 173
  • 273
1

this is less typing. It is not mandatory in this particular case. There is no reason to use this keyword unless if you want to pass the current instance of your object to a function for example.

You can simply write :

int getIntance() { return m_foo; } 

It is weird to call a method getInstance to return an int. It is quite uncommon...

Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62
0

There's no reason to use this, except when, for example, you want something outside the class to point to your instance (let's say, you add your instance - this - to a list of pointers).

In your example, this is redundant, since m_foo could easily have been returned by return m_foo; without any problem.

However, this can only be used in non-static member functions, or else it won't compile.

Iosif Murariu
  • 2,019
  • 1
  • 21
  • 27