Eissa N.
Eissa N.

Reputation: 1725

Pimpl idiom in C++ and private constructor

In pimpl idiom, all private members and functions are moved to a (private) implementation class. What should be done if a class has a private constructor? Should it be moved to the implementation? If yes, how?

class X {
private:
    X();  // moving it to XImpl???
public:
    void DoSomething();
private:
    class XImpl;
    std::unique_ptr<XImpl> pimpl;
};

Upvotes: 0

Views: 831

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145239

PIMPL is all about removing an undesired public header dependency, for various reasons. For example, C headers using the word class (correctness), large headers adding to the build time (work efficiency), headers with ungood macros (code brittleness). C++ accessibility, private versus public or protected, has nothing to do with it, although it's not at all unnatural if the accessibility correlates strongly with whether the features belong in the PIMPL class or not: usually those features will be implementation details.

Use a technique like PIMPL when you understand it and the technique is a good solution to the problem at hand.

Do not blindly apply various techniques based on cookbook-like mechanical rules. And when you clearly see that such a rule set that you're presented with, is incomplete, as here, then the proper reaction is to dismiss the rule set, not to ask for its completion. It can't be completed, the question that it leads to of what to do about a private constructor is meaningless.

Upvotes: 3

Related Questions