12.12.2012 Views

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

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.

Totally Immersed: <strong>C++</strong> Classes and Object-Oriented Programm<strong>in</strong>g<br />

HOUSE RULES: CLASS MEMBER FUNCTIONS<br />

■ Make public only those functions that users will need <strong>in</strong> order to properly utilize<br />

the class.<br />

■ Make private any functions that users do not need to know about.<br />

■ Make protected any functions that derived classes may need access to but that<br />

users do not need to know about.<br />

■ Use static member functions only under special circumstances.<br />

■ Declare any class member functions that have to be executed quickly as <strong>in</strong>l<strong>in</strong>e<br />

functions. Remember to keep <strong>in</strong>l<strong>in</strong>e functions short.<br />

■ Place any code duplicated more than twice <strong>in</strong> a function.<br />

What’s this?<br />

All classes have a hidden data member called this. this is a po<strong>in</strong>ter to the <strong>in</strong>stance of<br />

NEW TERM<br />

the class <strong>in</strong> memory. (A discussion on the this po<strong>in</strong>ter quickly starts to look like a<br />

“Who’s on First?” comedy sketch, but I’ll try anyway.)<br />

Obviously this (pun <strong>in</strong>tended) will require some explanation. First, let’s take a look at how<br />

the Rect class would look if this were not a hidden data member:<br />

class Rect {<br />

public:<br />

Rect();<br />

Rect(<strong>in</strong>t _left, <strong>in</strong>t _top, <strong>in</strong>t _bottom, <strong>in</strong>t _right);<br />

~Rect();<br />

<strong>in</strong>t GetWidth();<br />

<strong>in</strong>t GetHeight();<br />

void SetRect(<strong>in</strong>t _left, <strong>in</strong>t _top, <strong>in</strong>t _bottom, <strong>in</strong>t _right);<br />

private:<br />

Rect* this; // if ‘this’ were not <strong>in</strong>visible<br />

<strong>in</strong>t left;<br />

<strong>in</strong>t top;<br />

<strong>in</strong>t bottom;<br />

<strong>in</strong>t right;<br />

char* text;<br />

};<br />

This is effectively what the Rect class looks like to the compiler. When a class object is created,<br />

the this po<strong>in</strong>ter automatically gets <strong>in</strong>itialized to the address of the class <strong>in</strong> memory:<br />

TRect* rect = new TRect(20, 20, 100, 100);<br />

// now ‘rect’ and ‘rect->this’ have the same value<br />

// because both po<strong>in</strong>t to the object <strong>in</strong> memory<br />

107<br />

4

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

Saved successfully!

Ooh no, something went wrong!