driveForward(); // Just start driving forward driveForward(12); // Just drive for 12 inches driveForward(12,25); // Drive for 12 inches at 25% powerThe types of function overloading we use are classified as a form of static polymorphism in which a function call is resolved using the 'best match technique', i.e., the function is resolved depending upon the argument list.
task main() { driveForward(12); driveForward(12, 35); }Both of these functions will make the robot drive forward 12 inches. But the first one does so at the default power level and the second one does it at the specified power level.
// Declare a global variable for the defaultPowerLevel int defaultPowerLevel=20; // Define three driveForward() functions // First driveForward() definition includes distance and power as passed parameters (arguments) void driveForward(int distance, int powerLevel) { forward(distance*30, degrees, powerLevel); } // The second driveForward() function is defined to only use the distance parameter // The defaultPowerLevel is added inside the function to ANOTHER call // to the driveForward() function. Only the one inside uses both parameters. void driveForward(int distance) { driveForward(distance, defaultPowerLevel); } // The third driveForward() function is defined without passing any parameters // Inside this function, motors B and C are set to the default power level. void driveForward() { setMultipleMotors(defaultPowerLevel, B, C); } task main() { driveForward(12); driveForward(12, 35); driveForward(); untilDistance(12); stopMoving(); }
// Declare a global variable for the defaultPowerLevel int defaultPowerLevel=20; void driveForward(int distance, int powerLevel) { forward(distance*30, degrees, powerLevel); } void driveForward(int distance) { driveForward(distance, defaultPowerLevel); } void driveForward() { setMultipleMotors(defaultPowerLevel, B, C); } #define stopOnTouch() while(!SensorValue[touchSensor]) sleep(5); stopMoving() task main() { driveForward(); // Tells the robot to drive forward untilLine(); // until it sees a black line stopMoving(); // and then stop moving. driveForward(); // Tells the robot to drive forward untilTouch(); // until it bumps into the wall stopMoving(); // and then stop moving. driveForward(); // Tells the robot to drive forward stopOnTouch(); // and then stop moving when it touches the wall. }
circle(x, y, r); // draws a circle at position x, y with radius r circle(x, y); // draws a randomly sized circle at the specified location circle(r); // draws a circle with a specified radius at a random position on the LCD screen circle(); // draws a circle with a random radius at a random position on the LCD screenHint:
// To draw a circle at a random location... #define random(Limit) abs(rand()%Limit) void circle(int radius) { int x=random(100); int y=random(100); drawCircle(x, y, radius); }Exercise (exercise-in-function-overloading.htm)