Function returning this pointer in C ++

1st code:

#include <iostream>
using namespace std;
class demo
{
  int a;
public:
  demo():a(9){}
  demo& fun()//return type isdemo&
  {
    return *this;
  }
};

int main()
{
  demo obj;
  obj.fun();
  return 0;
}

Second code:

#include <iostream>
using namespace std;
class demo
{
  int a;
public:
  demo():a(9){}
  demo fun()//return type is demo
  {
    return *this;
  }
};

int main()
{
  demo obj;
  obj.fun();
  return 0;
}

What is the difference between these two codes since both work in gcc? I'm new here, so forgive me if my way of asking is wrong.

+5
source share
6 answers

demo & fun()returns a link to the current object. demo fun()returns a new object created by copying the current object.

+8
source

Besides what @Erik said about the return type, a little digression on this-pointer:
The following is equivalent:

struct my_struct{
  my_struct* get_this() const { return this; }
};

my_struct obj;
my_struct* obj_this = ob.get_this();

std::cout << std::boolalpha; // to display true/false instead of 1/0
std::cout << "&obj == obj_this = " << &obj == obj_this << "\n";

A pointer thisis just a pointer to this object, you can consider it hidden. This is more understandable in C:

typedef struct my_struct{
  int data;
  // little fidgeting to simulate member functions in c
  typedef void (*my_struct_funcptr)(struct my_struct*,int);
  my_struct_funcptr func;
}my_struct;
// C++ does something similar to pass the this-pointer of the object
void my_struct_func(my_struct* this, int n){
  this->data += n;
}

my_struct obj;
obj.data = 55;
// see comment in struct
obj.func = &my_struct_func;
obj.func(&obj, 15);
//       ^^^^ - the compiler automatically does this for you in C++
std::cout << obj.data; // displays 70
+5
source

, . demo& fun() , . , , :

#include <iostream>
struct test {
  int x;
  test() : x() {}
  test& foo() { return *this; }
  test bar() { return *this; }
  void set( int value ) { x = value; }
};
int main() {
  test t;
  t.foo().set( 10 );             // modifies t
  t.bar().set( 5 );              // modifies a copy of t
  std::cout << t.x << std::endl; // prints 10
}
+4

1 demo obj . obj 'demo(): a (9) {}'. obj.fun() ( ) obj.

2 obj.fun() demo ( ) .

+1

.

demo fun(){return *this;}

, , , .

, , , ( fun, ) .

, , . , . ( , , , , , ). , , , ( , ). main() / () . temp , - , ( main()), , .

, , , , obj ( ) , . .

+1

.

  • 1- fun()
  • fun() ( )
  • For the 1st case, if you decide to return by value, you prefer to return const Help; those. const demo& fun(); and later you can copy it if necessary. Just a return link makes the object can be modified, which may accidentally edit the content without intent
  • For the second case, DO NOT return the object by value, because it can create an unnecessary temporary copy that will affect the memory / performance of your code.
0
source

All Articles