I'm learning C++ and I'm just getting into virtual functions.
From what I've read (in the book and online), virtual functions are functions in the base class that you can override in derived classes.
But earlier in the book, when learning about basic inheritance, I was able to override base functions in derived classes without using virtual
.
So what am I missing here? I know there is more to virtual functions, and it seems to be important so I want to be clear on what it is exactly. I just can't find a straight answer online.
i think you are referring to the fact once a method is declared virtual you don't need to use the 'virtual' keyword in overrides.
If you don't use 'virtual' in Base's foo declaration then Derived's foo would just be shadowing it.
When you have a function in the base class, you can
Redefine
orOverride
it in the derived class.Redefining a method : A new implementation for the method of base class is given in the derived class. Does not facilitate
Dynamic binding
.Overriding a method:
Redefining
avirtual method
of the base class in the derived class. Virtual method facilitates Dynamic Binding.So when you said :
you were not overriding it as the method in the base class was not virtual, rather you were redefining it
Here is complete example that illustrates why virtual method is used.
Without "virtual" you get "early binding". Which implementation of the method is used gets decided at compile time based on the type of the pointer that you call through.
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.
EDIT - see this question.
Also - this tutorial covers early and late binding in C++.
We need virtual methods for supporting "Run time Polymorphism". When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.