I know how virtual
works in the context of member functions, but I saw an article online about virtual member classes that confuses me.
The example I found is this:
class Machine
{
void run () {}
virtual class Parts
{
};
};
// The inner class "Parts" of the class "Machine" may return the number of wheels the machine has.
class Car: public Machine
{
void run() {
cout << "The car is running." << endl;
}
class Parts
{
int get_Wheels () {
cout << "A car has 4 wheels." << endl;
return 4;
}
string get_Fuel_Type () {
cout << "A car uses gasoline for fuel." << endl;
return "gasoline";
}
};
};
The article at https://en.wikipedia.org/wiki/Virtual_class claims:
Any object of class type Machine can be accessed the same way. The programmer can ask for the number of wheels (by calling get_Wheels()), without needing to know what kind of machine it is, how many wheels that machine has, or all the possible types of machines there are. Functions like get_Fuel_Type() can be added to the virtual class Parts by the derived class Car.
How can one call get_Wheels()
or any other function in the member class Parts
from a Machine*
? It seems like you would have to know what kind of Machine
you have before being able to call get_wheels()
since you have no guarantee that the function has an implementation.