Public Group

# I don't understand -- References confusion.

This topic is 2791 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

EDIT: sorry, I don't know how to paste C++ code so it formats itself, I don't type everything left justified like it shows up.

Hello, I'll try to explain this as best I can. I'm having trouble understanding what this code is...saying...It's just an example exercise from a book, but I'm not sure how to 'say' to myself what this code is doing. Specifically the lines that are commented.

 #include <iostream> #include <conio.h> using namespace std; class CAT { public: CAT(int age) {itsAge = age;} ~CAT() {} int GetAge() const {return itsAge;} private: int itsAge; }; CAT &MakeCat(int age); //What is this 'saying'? int main() { int age = 7; CAT Boots = MakeCat(age); cout << "Boots is " << Boots.GetAge() << " years old." << endl; _getch(); return 0; } CAT &MakeCat(int age) { CAT *pCat = new CAT(age); return *pCat; } //also, the code compiles but the book says there is an error //probably a memory leak situation. Don't worry about it. 

I understand it's saying it returns a CAT object, but is it saying it's a reference function or something, what does a reference function mean?
I hope you can understand what I'm trying to ask.
Thank you.

##### Share on other sites
Couple of things..
1. What you new you must delete.
2. Returning an object allocated on the heap by reference is, usually, a VERY BAD IDEA. Not so much because it can't be done, you can do it, but because it is impossible for the CALLER of your code to know that you've allocated the object on the heap and thus that it must be released. More importantly though, by returning by reference is is trivial to create a copy, such as you did in the second line of your main method. Thereby losing the reference, and thereby leaking memory.
3. Its saying it returns a reference to a CAT.

##### Share on other sites
Oh! Ok, I get how to say what it's doing to myself now. Thanks, I'm aware the code is poor, it's from the exercise portion of the end of the chapter. It's trying to teach me what not to do.

Also, how do I format the C++ code so it shows up exactly as I type it? If i recall it's something like [code lang=c++] but I'm not 100%...Thanks!

##### Share on other sites
The code paste does not properly handle tabs, you can go into raw edit mode (the switch in the top left of the edit window), or just untabify the code.

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 15
• 11
• 9
• 11
• 15