return *this

*this at the end of a function
snippet:
 
return (*this);

I read that this is returning the class pointed to by "this". My question is how to use the returned information from (return *this)?
Last edited on
It can be used for chaining.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

using namespace std;

class MyClass
{
public:
  MyClass& print ()
  {
    cout << __FUNCTION__ << '\n';
    return *this;
  }
  MyClass& print2 ()
  {
    cout << __FUNCTION__ << '\n';
    return *this;
  }
};

int main ()
{
  MyClass myClass;
  myClass.print ().print2 ();
  return 0;
}
Thx, that worked fine! Going just a little deeper, what does returning *this in foo do to enable the calling of goo?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

#include<iostream>

class Moo
{
	private:
	public:
	Moo& foo()
	{
		std::cout<<"foo"<<std::endl;
		return *this;
	}
	Moo& goo()
	{
		std::cout<<"goo"<<std::endl;
		return * this;
	}
	Moo& hoo()
	{
		std::cout<<"hoo"<<std::endl;
		return * this;
	}
};

int main()
{
	Moo moo;
	moo.foo().goo().hoo();

	return 0;
}


foo
goo
hoo
Last edited on
Thx, that worked fine! Going just a little deeper, what does returning *this in foo do to enable the calling of goo?

Have a think about what kind of object is returned by foo().
Topic archived. No new replies allowed.