11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 14: Point and Stare at Objects 193MyClass* myFunc(){// the following does not workMyClass mc;MyClass* pMC = &mc;return pMC;}Upon return from myFunc(), the mc object goes out of scope. The pointerreturned by myFunc() is not valid in the calling function.The problem of returning memory that’s about to go out of scope is discussedin Chapter 9.Allocating the object off the heap solves the problem:MyClass* myFunc(){MyClass* pMC = new MyClass;return pMC;}The heap is used to allocate objects in a number of different situations.Comparing Pointers to ReferencesI hate to keep referencing pointers and pointing to references, but new programmersoften wonder why both are needed.Actually, you could argue that you don’t need both. C# and most other languagesdon’t use pointers. However, pointer variables are an ingrained part ofgood ol’ standard non-Visual Studio.NET–specific C++.Why Not Use References Rather Than Pointers?The syntax for manipulating a reference is similar to that used with normalobjects. So why not just stick with references and never look back at pointers?Objects and their addresses aren’t the same thing. Many times, the syntax fora reference actually becomes more complicated than that for pointers.Consider the following examples:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!