Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know when function has to be virtual?

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

like image 572
VextoR Avatar asked Mar 14 '11 09:03

VextoR


People also ask

When should a function be virtual?

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.

What are the rules to be considered for virtual 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.

Should all functions be virtual?

A function only needs to be virtual iff a derived class will implement that function in a different way.

What does it mean for a function to be virtual?

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.


1 Answers

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.

like image 53
Björn Pollex Avatar answered Oct 23 '22 04:10

Björn Pollex