The calcWage( ) function is like a Swiss army knife
You may need different tools for different jobs but all you need
is the single function.
C++ determines which version of the function to use,
by matching the number and type of parameters passed.
This is called early binding,
since the compiler can determine at compile time, which function to call.
A virtual function can be defined in the base class by using the keyword
virtual .
Using the previous example; the function in the base class would be:
virtual float calcWage( );
then in the derived class for hourly employees float calcWage( );
in the sales employee float calcWage( ); .
if(a == 3) {
b = b1;
} else if(a == 4) {
b = b2;
} // etc...
or the same code with switch-choice
switch(a) {
case: 3;
b = b1;
break;
case: 4;
b = b2;
break;
// etc...
Array of numbers will shorten this code:
int a=4;
int choices[8] = {1,2,3,4,5,6,7,8};
int b;
b = choices[a]; // DONE!
------------------------------------------
Function pointers: Consider a similar thing for function-choices
if(a == 3) {
function1();
} else if(a == 4) {
function2();
}
// etc...
You can arrange your functions into array:
*functions = {function1, function2, etc..}
functions[a](); // DONE!
---------------------------------------------
Hope you get the idea.
This idea was refactored in object-oriented programming into POLYMORPHISM.
Here is the example of drawing multiple shapes with structural code and with OOP.
Structural programming:
drawRect();
drawTriag();
etc..
if(a == 3) {
drawRect();
} else if(a == 4) {
drawTriag();
} // etc..
OOP - using inheritance and polymorphism
abstract class Shape {
virtual draw();
}
class Rect:Shape { // inherits from shape
draw() {
// real implementation that draws rectangle
}
}
class Triag:Shape { // also inherits Shape
draw() {
// real implementation that draws triangle
}
} // etc..
// the main application code
Shape s = getShape(); // returns an object of shape nature: Rect, Triag, etc.
s.draw(); // polymorphism! the draw() is a function of Rect or Triag that depends on a real-time s-object
---------------------------------------------------------------------------------------------