Search code examples
c++virtual

Virtual Function simply a function overloading?


So I came across something called Virtual Function in C++, which in a nutshell from what I understood is used to enable function overloading in derived/child classes.

So given that we have the following class:

class MyBase{
public:
    virtual void saySomething() { /* some code */ }
};

then when we make a new class that inherits MyBase like this:

class MySubClass : public MyBase{
public:
    void saySomething() { /* different code than in MyBase function */ }
};

the function in MySubClass will execute its own saySomething() function.

To understand it, isn't it same as in Java where you achieve the same by simply writing the same name of the function in the derived class, which will automatically overwrite it / overload it?

Where's in C++ to achieve that you need that extra step, which is declaring the function in base class as virtual?

Thank you in advance! :)


Solution

  • Well in c++ a virtual function comes with a cost. To be able to provide polymorphism, overloading etc you need to declare a method as virtual.

    As C++ is concerned with the layout of a program the virtual keywords comes with an overhead which may not be desired. Java is compiled into bytecode and execute in a virtual machine. C++ and native assembly code is directly executed on the CPU. This gives you, the developer, a possibility to fully understand and control how the code looks and execute at assembler level (beside optimization, etc).

    Declaring anything virtual in a C++ class creates a vtable entry per class on which the entire overloading thing is done.

    There is also compile time polymorphism with templates that mitigates the vtable and resolution overhead which has it's own set of issues and possibilities.