Main Menu


Sponsored Links

  


  
  
Web Cartoon Maker: a Fun Way to Learn C++ Contents Previous Next

Composition

As you should expect by now, once you define a new function, you can use it as part of an expression, and you can build new functions using existing functions. For example, what if someone gave you two points, the center of the circle and a point on the perimeter, and asked for the area of the circle?

Let’s say the center point is stored in the variables dXC and dYC, and the perimeter point is in dXP and dYP. The first step is to find the radius of the circle, which is the distance between the two points. We can write a function for that:

double GetDistance ( double dX1, double dY1, double dX2, double dY2)

{

double dX = dX2 - dX1;

double dY = dY2 - dY1;

double dSquared = dX*dX + dY*dY;

double dResult = Sqrt ( dSquared );

return dResult;

}

The second step is to find the area of a circle with that radius, and return it. Fortunately we already have a function for that. Wrapping all that up in a function we get:

double Fred ( double dXC, double dYC, double dXP, double dYP )

{

double dRadius = GetDistance ( dXC, dYC, dXP, dYP );

double dResult = GetArea ( dRadius );

return dResult;

}

The name of this function is Fred, which may seem odd. I will explain why in the next section. The temporary variables in these two functions are useful for development and debugging, but once everything is working we can make it more concise by composing the function calls:

double GetArea ( double dRadius)

{

return 3.1415926 * dRadius * dRadius;

}

double GetDistance ( double dX1, double dY1, double dX2, double dY2)

{

double dX = dX2 - dX1;

double dY = dY2 - dY1;

return dSquared = Sqrt ( dX*dX + dY*dY );

}

double Fred ( double dXC, double dYC, double dXP, double dYP )

{

return = GetArea ( GetDistance ( dXC, dYC, dXP, dYP ) );

}


Contents Previous Next
  
News

New Tales Animator Video by Alan Sturgess

Alan Sturgess shared an excellent video he made using Tales Animator! You can still download Tales Animator here. Unfortunately it is only available for Wi

...

Simple Online Character Designer

There is a prototype of simple online character designer available HERE. It is only a prototype, it does not contain many pieces yet but it can already generat

...

Book is updated

Now our book "Web Cartoon Maker: A Fun Way to Learn C++" is fully in synch with WCM 1.5! It is available for download and online reading HERE.

...

Web Cartoon Maker 1.5 is here!

Web Cartoon Maker 1.5 is finally here! You can download it HERE! Here is what was updated in version 1.5: Web Cartoon Maker Desktop Edition is now fully standal

...

read more news...


Poll