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

Recommended Answers

All 4 Replies

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.

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.

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.