Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance Costs in C++

Taking the following snippet as an example:

struct Foo
{
  typedef int type;
};

class Bar : private Foo
{
};

class Baz
{
};

As you can see, no virtual functions exist in this relationship. Since this is the case, are the the following assumptions accurate as far as the language is concerned?

  • No virtual function table will be created in Bar.
  • sizeof(Bar) == sizeof(Baz)

Basically, I'm trying to figure out if I'll be paying any sort of penalty for doing this. My initial testing (albeit on a single compiler) indicates that my assertions are valid, but I'm not sure if this is my compiler's optimizer or the language specification that's responsible for what I'm seeing.

like image 929
chrosph Avatar asked Jul 06 '10 23:07

chrosph


2 Answers

According to the standard, Bar is not a POD (plain old data) type, because it has a base. As a result, the standard gives C++ compilers wide latitude with what they do with such a type.

However, very few compilers are going to do anything insane here. The one thing you probably have to look out for is the Empty Base Optimization. For various technical reasons, the C++ standard requires that any instance be allocated storage space. For some compilers, Foo will be allocated dedicated space in the bar class. Compilers which implement the Empty Base Optimization (most all in modern use) will remove the empty base, however.

If the given compiler does not implement EBO, then sizeof(foo) will be at least twice sizeof(baz).

like image 113
Billy ONeal Avatar answered Oct 09 '22 09:10

Billy ONeal


Yeah, without any virtual members or member variables, there shouldn't be a size difference.

like image 21
Shawn D. Avatar answered Oct 09 '22 09:10

Shawn D.