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.

100 Day 4<br />

protected:<br />

void StartupProcedure();<br />

private:<br />

void StartElectricalSystem();<br />

void StartEng<strong>in</strong>e();<br />

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

bool started;<br />

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

};<br />

Notice that the constructor does not have a return type. A constructor cannot return a value,<br />

so no return type is specified. If you try to add a return type to the constructor declaration,<br />

you will get a compiler error.<br />

A class can have more than one constructor. This is possible through function overload<strong>in</strong>g,<br />

which I discussed on Day 3, “Up to Your Neck <strong>in</strong> <strong>C++</strong>.” For <strong>in</strong>stance, a class might have a<br />

constructor that takes no parameters (a default constructor) and a constructor that takes one<br />

or more parameters <strong>in</strong> order to <strong>in</strong>itialize data members to certa<strong>in</strong> values. For example, let’s<br />

say you have a class called Rect that encapsulates a rectangle (rectangles are frequently used<br />

<strong>in</strong> W<strong>in</strong>dows programm<strong>in</strong>g). This class could have several constructors. It could have a default<br />

constructor that sets all the data members to 0, and another constructor that allows you to<br />

set the class’s data members through the constructor. First, let’s take a look at how the class<br />

declaration might look:<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 />

<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 />

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

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

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

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

};<br />

The def<strong>in</strong>itions for the constructors, then, would look someth<strong>in</strong>g like this:<br />

Rect::Rect()<br />

{<br />

left = 0;<br />

top = 0;<br />

bottom = 0;<br />

right = 0;<br />

}<br />

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

{<br />

left = _left;<br />

top = _top;<br />

bottom = _bottom;<br />

right = _right;<br />

}

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

Saved successfully!

Ooh no, something went wrong!