#include <iostream>
usingnamespace 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.