2

Compile the following class

class Interface
{
  virtual void doIt() = 0;
  virtual ~Interface() = 0;
};

inline Interface::~Interface() {}

using gcc -fdump-class-hierarchy.

gcc emits

Class Interface
   size=4 align=4
   base size=4 base align=4
Interface (0x1a779c0) 0 nearly-empty
    vptr=((& Interface::_ZTV9Interface) + 8u)

What is the significance of "nearly-empty"? What does it mean?

Tobias
  • 6,388
  • 4
  • 39
  • 64
  • Not related but..Don't make virtual destructor as pure virtual as you are providing the implementation. – Naveen Jul 20 '09 at 11:21
  • 4
    I don't think that is particularly good advice. Pure virtual destructors are a common shorthand for saying the class is abstract, and they must have an implementation. –  Jul 20 '09 at 11:25
  • 1
    @Naveen: Why not? Any pure virtual function can have an implementation. – dalle Jul 20 '09 at 11:26
  • 5
    ... and destructors must have an implementation. – dalle Jul 20 '09 at 11:27

4 Answers4

7

C++ has something called an "empty base optimization". If a class has no members, it doesn't need to take up space when it's used as a base class. An example of why this is important is std::unary_function<T, U>. It exists to provide you with an easy set of typedefs. Those typedefs should not contribute to the size of your functor class.

If you have a base class with a vtable pointer, this pointer can likely be shared with the derived class. You simply create a vtable for the derived class which adds its own methods after that of the base class.

You can now achieve a similar "no extra overhead" base class. Apparently GCC calls that "nearly empty".

MSalters
  • 173,980
  • 10
  • 155
  • 350
6

I suppose it's to differentiate it from "empty", which is what you get if compile a class with no members at all. "nearly-empty" seems to mean it hasa vtable and nothing else.

4

The C++ ABI provides a definition of "nearly empty" classes and an interesting discussion of how they affect vtable construction:

A class that contains a virtual pointer, but no other data except (possibly) virtual bases. In particular, it:

  • has no non-static data members other than zero-width bitfields,
  • has no direct base classes that are not either empty, nearly empty, or virtual,
  • has at most one non-virtual, nearly empty direct base class, and
  • has no proper base class that is empty, not morally virtual, and at an offset other than zero.

I ran across this while researching the effect of nearly empty virtual bases on object size, vtable size, and virtual call overhead.

Trevor Robinson
  • 15,694
  • 5
  • 73
  • 72
3

It only has a vtable, no data fields.

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284