Suppose I have a class X
with private implementation Ximpl
:
//X.h
class X
{
void foo();
//..
private:
class Ximpl;
std::unique_ptr<X> x_impl;
}
Then there are several ways to structure the code. Perhaps the most common one is to put everything else into X.cpp
file, including Ximpl
class declaration, its methods and methods of X
class:
//X.cpp
#include"X.h"
class X::Ximpl
{
void bar();
//..
}
void X::Ximpl::bar()
{
//...
}
void X::foo()
{
//operate on x_impl
}
However there are other possibilities mentioned in different sources, which can improve the structure of code, but may diminish the advantages of using PIMPL idiom:
Have two cpp files:
X.cpp
- having only definitions ofX
methods, andXimpl.cpp
- having definitions fromXimpl
class. In this case inX.cpp
we'll have to#include "Ximpl.cpp"
- which is a bad practice, since cpp file would be compiled twiceHave separate header file
Ximpl.h
, which defines an implementation class, and put all definitions from bothXimpl
andX
classes in singleX.cpp
file. In this case, implementation class is declared in a header file and would be recompiled every time, loosing the certain advantages of PIMPLFinally, have 4 separate files - header file declaring
Ximpl
class, second header file declaringX
class, and two cpp files with implementations of above 2 classes respectively.
First, is all above correct? And, second, what is the best practice that works and satisfies all requirements? It looks that the first way (just 1 .h and 1 .cpp files) works great, but for large code bases it can quickly become cumbersome to navigate the projects, i.e. single cpp file would contain pimpl class declration, pimpl class definitions and base class definitions.