Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you want to put a class in an implementation file?

Tags:

While looking over some code, I ran into the following:

.h file

class ExampleClass
{
public:
    // methods, etc
private:
    class AnotherExampleClass* ptrToClass;
}

.cpp file

class AnotherExampleClass
{
    // methods, etc
}

// AnotherExampleClass and ExampleClass implemented 

Is this a pattern or something beneficial when working in c++? Since the class is not broken out into another file, does this work flow promote faster compilation times?

or is this just the style this developer?

like image 349
afuzzyllama Avatar asked Aug 13 '14 15:08

afuzzyllama


2 Answers

This is variously known as the pImpl Idiom, Cheshire cat technique, or Compilation firewall.

Benefits:

  • Changing private member variables of a class does not require recompiling classes that depend on it, thus make times are faster, and the FragileBinaryInterfaceProblem is reduced.
  • The header file does not need to #include classes that are used 'by value' in private member variables, thus compile times are faster.
  • This is sorta like the way SmallTalk automatically handles classes... more pure encapsulation.

Drawbacks:

  • More work for the implementor.
  • Doesn't work for 'protected' members where access by subclasses is required.
  • Somewhat harder to read code, since some information is no longer in the header file.
  • Run-time performance is slightly compromised due to the pointer indirection, especially if function calls are virtual (branch prediction for indirect branches is generally poor).

Herb Sutter's "Exceptional C++" books also go into useful detail on the appropriate usage of this technique.

like image 79
bgporter Avatar answered Oct 17 '22 20:10

bgporter


The most common example would be when using the PIMPL pattern or similar techniques. Still, there are other uses as well. Typically, the distinction .hpp/.cpp in C++ is rather (or, at least can be) one of public interface versus private implementation. If a type is only used as part of the implementation, then that's a good reason not to export it in the header file.

like image 20
Ulrich Eckhardt Avatar answered Oct 17 '22 22:10

Ulrich Eckhardt