Because of C++ nature of static-binding for methods, this affects the polymorphic calls.
From Wikipedia:
Although the overhead involved in this dispatch mechanism is low, it may still be significant for some application areas that the language was designed to target. For this reason, Bjarne Stroustrup, the designer of C++, elected to make dynamic dispatch optional and non-default. Only functions declared with the virtual keyword will be dispatched based on the runtime type of the object; other functions will be dispatched based on the object's static type.
So the code:
Polygon* p = new Triangle;
p->area();
provided that area()
is a non-virtual
function in Parent class that is overridden
in the Child class, the code above will call the Parent's class method
which might not be expected by the developer. (thanks to the static-binding I've introduced)
So, If I want to write a class to be used by others (e.g library), should I make all my functions to be virtual for the such previous code to run as expected?
p.area()
does not even compile. Maybe you meanp->area()
? Time to pick up a good book on C++, I'd say. – Stuffp->area()
invokesPolygon::area()
,Triangle::area
, or some other function, as long as it returns the correct answer. That is entirely the library's responsibility, and opaque to the library user. – Cathey