1

Theoretically, what is the overall overhead on a class with a virtual method. Is the overhead limited to calls to the virtual methods or will other non-virtual methods suffer overhead as well?

For example, when a class has a virtual destructor but all other methods are non-virtual.

class Vehicle
{ 
    int mass;

    public:
    Vehicle(int mass) : mass(mass) {}
    virtual ~Vehicle() {}
    int getMass() { return mass; }
};

class Car : public Vehicle 
{
    WheelSet* wheels;

    Car(WheelSet* ws) : Vehicle(1500), wheels(ws) {}
    ~Car() { delete wheels; }
    int getWheelCount() { return wheels->count; }
}

int main()
{
    Car* car = new Car(new WheelSet());
    Vehicle* v = car;

    int a = c->getWheelCount();  // calls non-virtual derived method
    int b = c->getMass();  // calls non-virtual base method from derived pointer
    int c = v->getMass();  // calls non-virtual base method from base pointer

    delete v;  // calls virtual method (the destructor)
}

Are there any overhead when calling these non-virtual methods? Or only virtual method calls have overhead (the call to the destructor in this case)?

EDIT:

The point of this question is to know whether the presence of virtual functions affect the performance of other non-virtual methods. Other questions on this forum already provided answers about the performance comparison of virtual/non-virtual/inline methods.

Hydren
  • 363
  • 2
  • 11
  • There will be (at least typically, idk if it can be implemented differently internally) an extra pointer in the class, pointing to the vtable for the class. – Justin Jun 23 '17 at 18:01
  • 1
    Perhaps it is useful to read up on virtual tables: http://www.learncpp.com/cpp-tutorial/125-the-virtual-table/ – AndyG Jun 23 '17 at 18:03
  • 1
    I wrote two article about vtable if you're interested http://lapinozz.github.io/learning/2016/02/03/Messing-with-vtables.html – lapinozz Jun 23 '17 at 18:06

0 Answers0