Following the quote from the user Steve314's answer on Why do we need virtual functions in C++?:
With "virtual" you get "late binding". Which implementation of the method is used gets decided at run time based on the type of the pointed-to object - what it was originally constructed as. This is not necessarily what you'd think based on the type of the pointer that points to that object.
I stumbled upon the following example:
class Shape
{
std::string name;
friend std::ostream& operator<<(std::ostream&, const Shape&);
public:
Shape(const std::string&);
virtual double circumference() = 0;
virtual ~Shape() {}
protected:
virtual void print(std::ostream&) const;
};
In the classes that inherit from Shape (e.g. Circle, Square...), virtual functions are overridden. Such is the case with the method circumference().
My question is as follows: if circumference() is an abstract method that cannot be called (since Shape is an abstract class), why do we make it a virtual function and not simply leave it being abstract and override it as usual in derived classes?
If I understand correctly, we make a method virtual to ensure "late binding". E.g. If we were to have the following block of code:
Shape *circle = new Circle();
double circ = circle->circumference();
with making circumference() virtual we ensure that the method of the class type of our pointed-to object will be called, and not the method of the "declared" type (here we want to call the method of the Circle class).
So, if calling circumference() of the class Shape in any way would cause a compile-time error (making it impossible to occur) why do we make it virtual and not just abstract?