Search code examples
c++inheritancevirtualoverhead

Overhead of C++ inheritance with no virtual functions


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;

}

Solution

  • 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.