views:

176

answers:

3

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.

+1  A: 

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

Shawn D.
A: 

As far as I know the compiler will optimize this correctly, if any optimizing is needed at all.

Xeross
+8  A: 

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

Billy ONeal
is there a way to turn off EBO ?
Gollum
@Gollum: Sure, two ways. 1. Consult your compilers' documentation to see if they provide such an option. 2. Make the base non-empty. Stick an unused `char` or `int` in there :)
Billy ONeal
Superb. Thanks for bringing my attention to EBO. :)
chrosph
`EBO` is worth knowing: it's the only valid justification for using `private` inheritance instead of composition :)
Matthieu M.