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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

102 Day 4<br />

NOTE<br />

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

left(_left),<br />

top(_top),<br />

bottom(_bottom),<br />

right(_right)<br />

{<br />

}<br />

Notice two th<strong>in</strong>gs <strong>in</strong> this code snippet. First, notice that the <strong>in</strong>itializer list is preceded by a<br />

colon. (The colon is at the end of the function header, so you may not have noticed it.) Notice<br />

also that each variable <strong>in</strong> the <strong>in</strong>itializer list is followed by a comma except the last variable.<br />

Forgett<strong>in</strong>g either of these two th<strong>in</strong>gs will cause compiler errors.<br />

On Day 3 I talked about references. You can have a class data member<br />

that is a reference, but the reference can only be <strong>in</strong>itialized <strong>in</strong> the<br />

<strong>in</strong>itializer list of the class and nowhere else. Here’s an example:<br />

class MyClass {<br />

public:<br />

MyClass();<br />

// other public stuff<br />

private:<br />

OtherClass& other;<br />

// other private stuff<br />

};<br />

MyClass::MyClass() :<br />

other(*new OtherClass) // must do this here!<br />

{<br />

}<br />

Attempts to <strong>in</strong>itialize the reference anywhere else will result <strong>in</strong> compiler<br />

errors.<br />

In most cases it doesn’t matter whether you <strong>in</strong>itialize your data members <strong>in</strong> the body of the<br />

constructor or the <strong>in</strong>itializer list. I have done it both ways, but I prefer the <strong>in</strong>itializer list.<br />

Destructors<br />

The destructor is a special function that is automatically called just before the object<br />

is destroyed.<br />

The destructor could be considered the opposite of the constructor. It is usually used to free any<br />

memory allocated by the class or do any other cleanup chores. A class is not required to have<br />

a destructor, but if it does, it can have only one. A destructor has no return value and takes no<br />

parameters. The destructor’s name must be the name of the class preceded by a tilde (~).<br />

NEW TERM

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

Saved successfully!

Ooh no, something went wrong!