I'm trying to grasp how to use virtual functions.

Would the following be correct? Also would I not include the virtual in the .cpp file of base?

And when defining the derived class, would I also declare the virtual function in the public of the derived class?

//BASE HEADER FILE

#ifndef BASE_H
#define BASE_H

class Base { 
public: 
    virtual double testFunc() = 0;
    int func2(); 
};

#endif

//BASE.CPP FILE 
#include "base.h" 

int Base::func2()
{
    return 5; 
}

//DERIVED HEADER FILE

#ifndef DER_H
#define DER_H

#include "base.h"

class Derived : public Base { 
public: 
    double testFunc();
};
#endif

//DER.CPP FILE 
#include "Der.h" 

double Derived::testFunc()
{
    return 3.2;
}

1 Answers

3
Tejendra On Best Solutions

You don't need to append virtual to a function already declared virtual in parent class. The virtual specifier specifies that a non-static member function is virtual and supports dynamic dispatch. It may only appear in the decl-specifier-seq of the initial declaration of a non-static member function (i.e., when it is declared in the class definition).

What is a virtual function

A virtual function is a member function which is declared within a base class and is re-defined(Overriden) by a derived class. 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.

Working of virtual functions(concept of VTABLE and VPTR)

If a class contains a virtual function then compiler itself does two things:

  1. If object of that class is created then a virtual pointer(VPTR) is inserted as a data member of the class to point to VTABLE of that class. For each new object created, a new virtual pointer is inserted as a data member of that class.
  2. Irrespective of object is created or not, a static array of function pointer called VTABLE where each cell contains the address of each virtual function contained in that class.

For detailed information on virtual functions there are already plenty of good answers How are virtual functions and vtable implemented?