Why even use virtual functions in a Parent class?
[quote name='wayneprim' timestamp='1346827465' post='4976722']
What difference does the virtual function declaration in the Automobile class make? Couldn't I skip the declaration in automobile function since it is really not even a function (it does nothing) and just declare the function as normal in the Ferrari class? and if i made more child classes of the parent class Automobile, i could do the same?
Well, you could've just tried it out!
Anyway, here's the solution:
If you do not have a "drivespeed" function in "Automobile", your main would not compile.
If you'd make it not virtual, then your main would call the "drivespeed" function of the "Automobile" class and not of "Ferrari".
And that's exactly what polymorphism is. You can use a pointer to the base class to call a virtual function and it will automatically call the function implementation that matches the actual class.
Additionally, you state that the "drivespeed" function doesn't really make sense, because the speed of an "Automobile" is unknown. This can also be expressed in C++ by making the function "pure virtual".
[/quote]
Perfect explanation. Thanks a lot
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement