2

Following program output is correct but there comes a error when I use this in place of *this.Can anybody tell me what this and *this means

#include<iostream>
using namespace std;

class Test 
{
private:
    static int count;
public:
    Test& fun(); // fun() is non-static now
};

int Test::count = 0;

Test& Test::fun() 
{
    Test::count++;
    cout<<Test::count<<" ";
    return *this;
}

int main()  
{
    Test t;
    t.fun().fun().fun().fun();
    return 0;
}

Output:

1 2 3 4

When I use this in place of *this error comes:

In member function 'Test& Test::fun()':
invalid initialization of non-const reference of type 'Test&' from an rvalue of type 'Test*'
     return this;

Can anybody tell me what is the difference between this and *this by giving a good example?

m.s.
  • 16,063
  • 7
  • 53
  • 88
  • 3
    Possible duplicate of [What is the 'this' pointer?](http://stackoverflow.com/questions/16492736/what-is-the-this-pointer) and [What does “dereferencing” a pointer mean?](http://stackoverflow.com/questions/4955198/what-does-dereferencing-a-pointer-mean) – Mohamad Elghawi Oct 19 '15 at 11:41

1 Answers1

8

Can anybody tell me what this and *this means

this is a pointer to the current object.

*this is the current object.

You are aware, presumably, what the dereference operator does? I have no idea why you're arbitrarily trying to swap this for *this. Simply don't do that.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055