(*this)

Would anyone help the following declaration:

class Foo {
int test1();
std::string test2();
}

in a function, a declation as below, what it means ? please help

Foo foo(*this)

Thank you.
may need more context ... but off the cuff, it looks like

type variable(initialization)
eg
create a variable of type Foo
name it foo
and call a constructor to initialize it to *this.

*this is the current instance of the class.

so if you had
foo x;
and called that function
x.func()

then inside that function,
*this means "x".

if you called it again later for foo y, *this means "y". Its a handle back to itself, which is the only way to do some things.



this is a pointer to this instance, while the * in front, as with other pointers, would dereference it.

Quoting from a really awesome example
If you had a function that returned this, it would be a pointer to the current object, while a function that returned *this would be a "clone" of the current object, allocated on the stack -- unless you have specified the return type of the method to return a reference.


https://stackoverflow.com/questions/2750316/this-vs-this-in-c

Partial example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Foo
{
public:
//...
    Foo get_copy()
    {
        return *this;
    }

    Foo& get_copy_as_reference()
    {
        return *this;
    }

    Foo* get_pointer()
    {
        return this;
    }
//...
};


Operations that make changes to Foo reference returned by get_copy_as_reference() or the Foo* from get_pointer() do remain.
Topic archived. No new replies allowed.