Search code examples
c++forward-declaration

Declare a forwarded class definition in a cpp file, what for?


What is the point of forwarding a class definition in a .cpp file?

Imagine that I have a private class inside another public class. I forward the definition of the private class, like class Private.

Is there any advantages to putting the declaration of my private class in a .cpp file or should I just stick with my forward declaration in my public class.h and include my privateClass.h in the cpp file?


Solution

  • Internal classes and structs are often best kept out of public headers to avoid dependencies and coupling.

    If stuff is in the public header, it will mean that the public header will have to change if an implementation detail (in your private class/struct) changed. This is bad, because client programs will actually need to be recompiled (under the ODR - one definition rule) and various implementation defined consequences on class/vtable layout and or name mangling.

    Once you can avoid depending on the definition of your complete private type, you will avoid having all the unneeded dependencies, leading to

    1. reduced time to rebuild
    2. avoid unintended dependencies by client code on implementation private details

    A forward declared class is known as 'incomplete type' until it is defined (usually in a private header file or simply in the cpp file itself). Until that moment, only address-of, reference, pass by reference or pass by pointer are allowed. Sometimes incomplete classes can lead to tricky semantic situations; object destruction for an incomplete type will assume a non-virtual destructor (some compilers can detect this and warn if the actual definition introduces a virtual destructor). This plays a significant role when defining smart-pointers to incomplete types, e.g. in the popular pImpl idiom. Per-use the documentation of your smart pointer library (e.g. Boost SmartPtr) when in doubt.

    Update Adding backgrounder links since this is getting a popular answer: