0

what's the difference between the following two snippets of code? In a. B is returned; in b. B& is returned.
a.
class B
{
public: int i;
};

class D
{
public:
B fd(){B db; db.i=2; return db;}
};

b.
class B
{
public: int i;
};

class D
{
public:
B& fd(){B db; db.i=2; return db;}
};

3
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by Ancient Dragon
0

In the first version, a value of type B is returned.

And as you can see, in the second version, a value of type B& is returned.

0

The second version is actually illegal because the object being returned is created on the stack, and that object is destroyed when the function returns, therefore it will not exist and the returned reference will be invalidated.

The first version (without reference) is ok because the program will actually duplicate the class when it is returned.

0

Actually if you run the code on VC++2005, both will return 2.
#include <iostream> // Must #include this to use "placement new"
#include <string>
using namespace std;
1.
class B
{public: int i;};

class D
{
public:
B& fd(){B db; db.i=2; return db;}
};

int main()
{B b; D d; b=d.fd(); cout<<b.i<<endl;}

2.
#include <iostream> // Must #include this to use "placement new"
#include <string>
using namespace std;

class B
{public: int i;};

class D
{
public:
B fd(){B db; db.i=2; return db;}
};

int main()
{B b; D d; b=d.fd(); cout<<b.i<<endl;}

0

>>{B b; D d; b=d.fd(); cout<<b.i<<endl;}
In program 1 that only works because it isn't using the reference that was returned but its using another copy of that class. Try this and retest: {D d; B& b=d.fd(); cout<<b.i<<endl;}

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.