Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overhead of C++ inheritance with no virtual functions

Tags:

In C++, what's the overhead (memory/cpu) associated with inheriting a base class that has no virtual functions? Is it as good as a straight up copy+paste of class members?

class a { public:     void get(); protected:     int _px; }  class b : public a {  } 

compared with

class a { public:     void get(); protected:     int _px; }  class b { public:     void get(); protected:     int _px;  } 
like image 263
jameszhao00 Avatar asked Aug 14 '09 18:08

jameszhao00


People also ask

What happens if we don't use virtual function in inheritance?

If you don't use virtual functions, you don't understand OOP yet. Because the virtual function is intimately bound with the concept of type, and type is at the core of object-oriented programming, there is no analog to the virtual function in a traditional procedural language.

What is the overhead of calling a virtual function?

Calling a virtual function is fast — almost as fast as calling a non-virtual function. You don't get any additional per-call overhead no matter how deep the inheritance gets. You could have 10 levels of inheritance, but there is no “chaining” — it's always the same — fetch, fetch, call.

How is virtual function related to inheritance?

Base classes can't inherit what the child has (such as a new function or variable). Virtual functions are simply functions that can be overridden by the child class if the that child class changes the implementation of the virtual function so that the base virtual function isn't called.

Why do we need virtual functions in C?

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.


2 Answers

There might a be slight memory overhead (due to padding) when using inheritance compared to copy and past, consider the following class definitions:

struct A {   int i;   char c1; };  struct B1 : A {   char c2; };   struct B2 {   int i;   char c1;   char c2; }; 

sizeof(B1) will probably be 12, whereas sizeof(B2) might just be 8. This is because the base class A gets padded separately to 8 bytes and then B1 gets padded again to 12 bytes.

like image 192
cmeerw Avatar answered Dec 20 '22 21:12

cmeerw


It will take very slightly longer to compile, and there will be no additional runtime overhead. From the optimizer's perspective, non-virtual methods are the same as procedures -- they can be called using only their memory address, without overhead from a virtual method table.

like image 24
John Millikin Avatar answered Dec 20 '22 19:12

John Millikin