Speed up each car 5 times using the ICar interface

theCars[i]-> CurrentSpeed(& currSp); cout << " -> Speed: " << currSp << endl;

delete[] *theCars; return 0;

"C:\Apress Boaks\lnteropBook\Lab... | Ei

X

T am a basic csr

Jk.

->Speed: IB

[ am a hot rod?

200

[ am a basic car

->Speed: 20

I am a liot rod?

->Speed: 400

I am a basic car

->£peed: 30

[ am a hot rod?

->Speed: &0R

[ am a basic car

->Speed: 40

[ am a hot rodf

->Speed: B00

I am a basic car

->Speed: S0

I am a tint i"odt

->Speed: 1000

Press any key to continue

zl

< _

Figure 2-3: Driving your cars using interface references Here, the main() function creates an array of ICar pointers, each member of which is set to a unique automotive type. Given that both Car and HotRod implement the behavior defined by ICar, you are able to interact with each type using a simple ICar reference. However, because each class responds uniquely to the same request ("Speed up by delta") we have injected polymorphic behavior into the application. Consider Figure 2-4, which illustrates this concept using the popular COM lollipop notation.

Figure 2-3: Driving your cars using interface references Here, the main() function creates an array of ICar pointers, each member of which is set to a unique automotive type. Given that both Car and HotRod implement the behavior defined by ICar, you are able to interact with each type using a simple ICar reference. However, because each class responds uniquely to the same request ("Speed up by delta") we have injected polymorphic behavior into the application. Consider Figure 2-4, which illustrates this concept using the popular COM lollipop notation.

Figure 2-4: Polymorphic behavior a la interface-based programming Interfaces Are Strongly Typed Variables

In addition to the fact that you can manipulate classes using interface references, you are able to use interfaces as method parameters (and return types). For example, if you had a global method named RevEngine() which takes an ICar* as its sole argument as follows:

// Rev the engine of a given automobile.

void RevEngine(ICar* pCar) {

pCar-> CurrentSpeed(& currSp);

cout << "Speed: " << currSp << endl;

pCar-> CurrentSpeed(& currSp);

cout << "Speed: " << currSp << endl;

you can safely pass in any type that supports the ICar interface, as shown here:

// Make some cars and rev the engines.

ICar* pAnotherCar = new Car();

ICar* pAnotherHotRod = new HotRod();

RevEngine(pAnotherCar);

RevEngine(pAnotherHotRod);

delete pAnotherCar;

delete pAnotherHotRod;

If you attempt to pass in an incompatible type (such as a CellPhone object): // The CellPhone class does not implement ICar!

CellPhone cp; RevEngine(cp); // Error!

you will (thankfully) be issued a compile time conversion error:

error C2664: 'RevEngine' : cannot convert parameter 1 from 'class CellPhone'

Was this article helpful?

0 0

Post a comment