Here is quick help to understand the virtual mechanizm in general C++ terms.
In other words, it is polymorphism. It is multiple forms or multiple of shapes of a
single thing, or a single interface for multiple forms of interaction.
This can be achieved by function overloading, operator overloading etc etc in C++.
For example, if you want to define a class with a bare basic functionality and allow its
derived classes to customize or override that basic functionality, you provide
a single interface/function to handle those varying definitions in run-time without too much
hectic code.
That is the time you would want to design such class with virtual functionality.
Example, a base Flight class which defines a bare basic functionality for flying speed,
engine capacity, altitude etc. These characteristics/functions are varied by the engine
capacity or flight type, such as derived classes, helicopter, a propeller engine, and jet engine.
You would define these varying fucntionalities within each derived flight class overriding
the base class provided bare/basic functionality.
And you want to provide a single functional interface to handle all types flights,checking
the object being processed and its overriding functionality.
As you may have already knew that a base class type pointer can recognize/identify its derived
child class down to the leaf level of hierarchy. Hence a base class type pointer parameter
in a function signature and handles to check/process the varying functionality of children,
would do a right job.
Quick example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
void interface(Flight *pFlight)
{
if (dynamic_cast<Helicopter *>(pFlight)) // returns null if not
{
// .. handle the helicopter functionality
}
else if (dynamic_cast<Propeller *>(pFlight)) // returns null if not
{
// .. handle the propeller-operated flight functionality
}
if (dynamic_cast<Jet *>(pFlight)) // returns null if not
{
// .. handle the jet-operated flight functionality
}
}
int main()
{
// here you provide an interface to the client
Flight *myFlight;
Helicopter helicopter; //for client-1
interface( &helicopter );
Propeller propeller; // for client-2
interface( &propeller );
Jet jet;
interface( &jet ); // for client-3
// other common functionality
// all done
}
|
Here you provided one single interface for all type objects of a single family.
The dynamic_cast<> helps you to identify which child object is exactly pointed-to and what
functionality to be taken care of. This is done in run-time dynamically.
Hope this gives some idea of virtual or polymorphic functionality provided in C++.
For more details, you could check reference searching on "polymorphism".
Good luck :)