Why do we need virtual functions in C++?

前端 未结 26 3211
北恋
北恋 2020-11-21 05:50

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

26条回答
  •  春和景丽
    2020-11-21 06:13

    The virtual keyword forces the compiler to pick the method implementation defined in the object's class rather than in the pointer's class.

    Shape *shape = new Triangle(); 
    cout << shape->getName();
    

    In the above example, Shape::getName will be called by default, unless the getName() is defined as virtual in the Base class Shape. This forces the compiler to look for the getName() implementation in the Triangle class rather than in the Shape class.

    The virtual table is the mechanism in which the compiler keeps track of the various virtual-method implementations of the subclasses. This is also called dynamic dispatch, and there is some overhead associated with it.

    Finally, why is virtual even needed in C++, why not make it the default behavior like in Java?

    1. C++ is based on the principles of "Zero Overhead" and "Pay for what you use". So it doesn't try to perform dynamic dispatch for you, unless you need it.
    2. To provide more control to the interface. By making a function non-virtual, the interface/abstract class can control the behavior in all its implementations.

提交回复
热议问题