Question

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;

}
Was it helpful?

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.

OTHER TIPS

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.

If you forget virtual inheritance, having a base class is equivalent, memory and performance wise, to having a member of the same class. Excepted that it can sometimes be even better (for instance an empty class has a size of at least one but having an empty base class may often have no overhead).

If you might have a pointer of type Base* that points to an object of type Derived*, you probably need a virtual destructor and your original premise no longer applies. If the derived class has an empty destructor, and it has no members or they're all POD types, you can get away without a virtual destructor, but it's usually better to play it safe and make it virtual from the start.

The compiler will generate a direct call to the code implementing each non-virtual member function, thus there is no overhead.

Not really, it only increased the memory by the base class. You can read more in here in C++ FAQ

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top