[Cpp]
# Include <iostream>
Using namespace std;
Class Vehicle // Transportation
{
Public:
Void run () const // when it is defined as a virtual function, the pointer calls the virtual member function with the same name and executes the member function of the derived class. Objects cannot be directly accessed when defined as pure virtual functions.
{
Cout <"run a vehicle." <endl;
}
};
Class Car: public Vehicle // Car
{
Public:
Void run () const
{
Cout <"run a car." <endl;
}
};
Class Airplane: public Vehicle // aircraft
{
Public:
Void run () const
{
Cout <"run a airplane." <endl;
}
};
Int main ()
{
Cout <"(a) directly access member functions using objects:" <endl;
Vehicle v;
V. run ();
Car car;
Airplane airplane;
Car. run ();
Airplane. run ();
Cout <"(B) uses a pointer to the base class to access the member function:" <endl;
Vehicle * vp;
Vp = & car;
Vp-> run ();
Vp = & airplane;
Vp-> run ();
Return 0;
}
# Include <iostream>
Using namespace std;
Class Vehicle // Transportation
{
Public:
Void run () const // when it is defined as a virtual function, the pointer calls the virtual member function with the same name and executes the member function of the derived class. Objects cannot be directly accessed when defined as pure virtual functions.
{
Cout <"run a vehicle." <endl;
}
};
Class Car: public Vehicle // Car
{
Public:
Void run () const
{
Cout <"run a car." <endl;
}
};
Class Airplane: public Vehicle // aircraft
{
Public:
Void run () const
{
Cout <"run a airplane." <endl;
}
};
Int main ()
{
Cout <"(a) directly access member functions using objects:" <endl;
Vehicle v;
V. run ();
Car car;
Airplane airplane;
Car. run ();
Airplane. run ();
Cout <"(B) uses a pointer to the base class to access the member function:" <endl;
Vehicle * vp;
Vp = & car;
Vp-> run ();
Vp = & airplane;
Vp-> run ();
Return 0;
}