A normal function is linked in your program at compile time so when your program executes, the function will be called.
You have no ability to change the function call while the program is running.
This is kinda bad where you have a sort that needs to sort in various sequences that won't be known until the user enters choices from the keyboard.
Enter the function pointer.
A function pointer is a pointer that contains the address of a function.
With this in mind, assume you have this:
-
class Shape
-
{
-
public:
-
void draw() {cout << "I am a Shape" << endl;}
-
};
-
class Circle : public Shape
-
{
-
public:
-
void draw() {cout << "I am a Circle" << endl;}
-
-
};
-
-
void Process(Shape& s)
-
{
-
s.draw();
-
}
-
-
int main()
-
{
-
Circle c;
-
Process(c);
-
}
-
What you will see is the call to Process uses a derived object. The Process() function can accept this because a Circle IS-A Shape. However, when
s.draw() is called you see "I am a Shape" because Process() believes it has a Shape object.
This is not the desired output.
If you make the draw() function virtual, the compiler is told that if it has a choice between Shape::draw() or Circle::draw(), then you want to call Circle::draw().
To make this happen, a run-time decision needs to be made inside Process() to call the correct draw() function. That means a function pointer needs to be selected. The compiler accomplishes by building a table of function pointers for the virtual functions of a class and then placing the address of the table (called the VTBL) inside the object.
Then anytime the object is used and a virtual function is needed, the compiler generates code to look the function up in the VTBL and call it by address. All of this is hidden from you.
The effect is that you now see "I am a Circle" inside Process() because it is a Circle object that is really being used and the draw() is virtual so the address of the draw() is looked up in the VTBL. What is there is Circle::draw() because Circle overrode the Shape draw() method.
In effect, a virtual function is how C++ implements polymorphism.
Using polymorphism is commonly call
Object-Oriented Programming.