While describing a class, how to know when function has to be virtual?
I know what virtual function means, but I just can't figure out when I should make them virtual
Thanks
We use virtual functions to ensure that the correct function is called for an object, regardless of the reference type used to call the function. They are basically used to achieve the runtime polymorphism and are declared in the base class by using the virtual keyword before the function.
Rules for Virtual FunctionsA virtual function can be a friend function of another class. Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism. The prototype of virtual functions should be the same in the base as well as derived class.
A function only needs to be virtual iff a derived class will implement that function in a different way.
A virtual function is a member function that you expect to be redefined in derived classes. 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.
Functions should be virtual if you want to invoke them polymorphically. In other words, virtual function express behavior that can be customized in subclasses. For instance, consider the following class:
class Car {
public:
const std::string & getId() const;
virtual void startEngine() = 0;
private:
std::string id;
}
Every car has an Id
, and there is no customization allowed here, so there is no point in making it virtual. Subclasses should not be able to modify that property. How the engine is started however, depends on the specific car, and can in fact not be defined globally. But we do know that every car has to start the engine before we can drive, so we define it as a pure virtual function.
An important guideline for when to make a function virtual, and when not, is given by the Non-Virtual Interface idiom.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With