justthom8 justthom8 - 1 year ago 72
C++ Question

Class initialization list with struct pointer

I am looking at an example of the PIMPL idiom, and I found a line of code I really don't understand. Since I'm new to c++, and OOP, I was hoping somebody could explain what this function does.

Can somebody clarify this function?

PublicClass::PublicClass(const PublicClass& other)
: d_ptr(new CheshireCat(*other.d_ptr)) { // <------- This line
// do nothing


Here is the example.

//header file:
class PublicClass {
PublicClass(); // Constructor
PublicClass(const PublicClass&); // Copy constructor
PublicClass(PublicClass&&); // Move constructor
PublicClass& operator=(const PublicClass&); // Copy assignment operator
~PublicClass(); // Destructor
// Other operations...

struct CheshireCat; // Not defined here
unique_ptr<CheshireCat> d_ptr; // opaque pointer


//CPP file:
#include "PublicClass.h"

struct PublicClass::CheshireCat {
int a;
int b;

: d_ptr(new CheshireCat()) {
// do nothing

PublicClass::PublicClass(const PublicClass& other)
: d_ptr(new CheshireCat(*other.d_ptr)) {
// do nothing

PublicClass::PublicClass(PublicClass&& other)
d_ptr = std::move(other.d_ptr);

PublicClass& PublicClass::operator=(const PublicClass &other) {
*d_ptr = *other.d_ptr;
return *this;

PublicClass::~PublicClass() {}

Answer Source

C++ by default provides a copy constructor when the user does not define one: http://en.cppreference.com/w/cpp/language/copy_constructor

The line:

d_ptr(new CheshireCat(*other.d_ptr))

is simply dereferencing a pointer to an existing CheshireCat object and copying it to instantiate a new CheshireCat object that the d_ptr to the instantiated object points to.