Reputation: 7301
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;
}
Upvotes: 25
Views: 13394
Reputation: 7356
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.
Upvotes: 35
Reputation: 308158
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.
Upvotes: 3
Reputation: 52284
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).
Upvotes: 4
Reputation: 200796
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.
Upvotes: 17