Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function returning this pointer in c++

Tags:

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;
}

2nd 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 as both are working in gcc?i am new here so forgive me if my way of asking is wrong.

like image 955
Gautam Kumar Avatar asked Apr 20 '11 11:04

Gautam Kumar


People also ask

Can a function return a pointer C?

Pointers in C programming language is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function.

How can a function return a value from a pointer?

Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.

Can we return local pointer in C?

In C/C++, it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns. So to execute the concept of returning a pointer from function in C/C++ you must define the local variable as a static variable.

Can we declare a function that can return a pointer to a function of the same type?

You cannot return a function in C - you return a pointer to a function. If you mean to define a function which returns a pointer to a function which again returns a pointer to a function and so on, then you can use typedef to implement it.


1 Answers

demo & fun() returns a reference to the current object. demo fun() returns a new object, made by copying the current object.

like image 70
Erik Avatar answered Oct 04 '22 02:10

Erik