Solution: PImpl Idiom

Get a detailed explanation of the solution to the PImpl exercise.

We'll cover the following...

Solution

Press + to interact
main.cpp
public.cpp
public.h
#include <iostream>
#include <string>
#include "public.h"
class PublicClass::PImplClass {
public:
void DoPrivateStuff() {
std::cout << className << "::privateMethod\n";
}
private:
std::string className = "PublicClass";
};
PublicClass::PublicClass(): pImpl(new PImplClass) {}
PublicClass::~PublicClass() = default;
void PublicClass::publicMethod() {
std::cout << "PublicClass::publicMethod\n";
pImpl->DoPrivateStuff();
}

Code explanation

  • public.h file:

    • Lines 5–7: We already declared three public methods in the PublicClass: Constructor, Destructor, and a publicMethod. In this public method, we will access the
...