ar*****@gmail.com posted:
Since the virtual Keyword is specified,why can't the
compiler decide at the runtime itself,which function is to be
called,even if the function is called by the base class pointer??
That's exactly the aim: If you declare the function as "virtual", then the
compiler will make sure that the correct function is invoked, regardless of
the type of the expression.
By having the "virtual" keyword in C++, we are simply given the choice as to
whether we desire this behaviour.
Choice is good.
For instance, if we are writing a carwash program, then we can decide that
we'll wash a certain vehicle the way in which a car should be washed... or
we can just give it the generic vehicle wash:
void PerformCarwash( Vehicle& vehicle )
{
int money = AcceptMoney();
if ( 5 <= money ) WashVehicle( vehicle.GetWashingInfo() );
}
If the member function "GetWashingInfo" is virtual, then, if this vehicle is
a car, then it will be washed in a manner fitting a car. If however
"GetWashingInfo" is non-virtual, then it will just be given the generic
vehicle wash.
-Tomás
-Tomás