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.

NOTE<br />

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

void ShutDown();<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 how you break the class organization down <strong>in</strong>to the three access levels. You may not<br />

use all three levels of access <strong>in</strong> a given class. You are not required to use any of the access levels<br />

if you don’t want, but typically you will have a public and a private section at the least.<br />

Constructors<br />

Class-member access defaults to private. If you do not add any access<br />

keywords, all data and functions <strong>in</strong> the class will be private. A class<br />

where all data members and functions are private is not very useful <strong>in</strong><br />

most cases.<br />

Classes <strong>in</strong> <strong>C++</strong> have a special function called the constructor.<br />

The constructor is a function that is automatically called when an <strong>in</strong>stance of a class<br />

is created.<br />

The constructor is used to <strong>in</strong>itialize any class member variables, allocate memory the class will<br />

need, or do any other startup tasks. The Vehicle example you just saw does not have a<br />

constructor. If you do not provide a constructor, the <strong>C++</strong>Builder compiler will create a default<br />

constructor for you. While this is OK for simple classes, you will almost always provide a<br />

constructor for classes of any significance. The constructor must have the same name as the<br />

name of the class. This is what dist<strong>in</strong>guishes it as a constructor. Given that, let’s add a<br />

constructor declaration to the Vehicle class:<br />

NEW TERM<br />

class Vehicle {<br />

public:<br />

Vehicle(); // constructor<br />

bool haveKey;<br />

bool Start();<br />

void SetGear(<strong>in</strong>t gear);<br />

void Accelerate(<strong>in</strong>t acceleration);<br />

void Break(<strong>in</strong>t factor);<br />

void Turn(<strong>in</strong>t direction);<br />

void ShutDown();<br />

99<br />

4

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

Saved successfully!

Ooh no, something went wrong!