Query about returning references

Here's a piece of code that'll help explain my confusion:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
using namespace std;

class Person
{
private:
	int Age;

public:

	void SetAge(int age)
	{
		Age = age;
	}


	int GetAge() const
	{
		return Age;
	}
};

const Person & TheFunction() //returns constant reference
{
	Person * ptr = new Person;
	ptr->SetAge(19);
	cout <<"ptr : " << ptr << endl;
	return (*ptr);  
}

int main()
{
	Person A;
	A = TheFunction();  //TheFunction() returns a 'const' reference to an object on free store
	                    //but can an object(LHS) be assigned to a reference(RHS)?? 


	cout << "A : " << &A << endl; //Just to check if A has the same address as ptr; it doesn't
	
	cout << A.GetAge() << endl;

	A.SetAge(20); // A was assigned to a 'const' reference, so it should not allow this
	              //call to SetAge be possible ?!?!

	cout << A.GetAge() << endl; //Yet the age changes to 20!
	
	return 0;
}


I've commented out what i'm not sure about...

I need someone to explain this to me because right now i'm studying unary operator overloading, and i can't understand why the operator++() function returns a reference to a constant object rather than simply to an object.
TheFunction is incorrect. It allocates a Person object on the heap and returns a const reference to it. The semantics imply that the pointer will never be freed.

In main where TheFunction is used, the return value is assigned to A. The means that a copy is taken and the pointer is lost for ever and that memory can never be free, we call this garbage. Some languages (Java, C#) recover this autmatically at a runtime cost, but C++ doesn't.
thanks kbw...
makes a little more sense to me now ;)
cheers :)
Topic archived. No new replies allowed.