views:

658

answers:

5

Hi,

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;

}
+1  A: 

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

vehomzzz
I'm aware there's a function-table cost as soon as virtual functions are introduced. I'm wondering how the C++ compiler processes inheritance with no polymorphism.
jameszhao00
for one, it doesn't allocate memory for vtable, doesn't create a vpointer in the base class, thus both compiler and runtime takes less than with virtual function/dtors. what are you trying to accomplish?
vehomzzz
+4  A: 

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.

John Millikin
Why would it take longer to compile? just curious. I thought compiler's were smart enough these days :)
vehomzzz
The increased time will be only a few milliseconds, since the compiler will have to construct the inheritance tree. It's not worth caring about.
John Millikin
+1  A: 

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

AProgrammer
+1  A: 

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.

Mark Ransom
+4  A: 

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.

cmeerw
Ah nice observation.
jameszhao00
All the other answers are valid, but this is something I didn't know/think of before.
jameszhao00