I'm attempting to use the PIMPL idiom. This is my public header file in include/foo.h
:
class FooPrivate;
class Foo {
public:
Foo();
~Foo();
private:
FooPrivate* p_impl;
};
The private class is defined in: src/foo_private.h
and used throughout src/*.cpp
:
class FooPrivate {
public:
...
private:
...
};
My question is, what are the reasons to distinguish public:
or private:
members and functions in FooPrivate
since the entire class is private? This is from the perspective of distributing foo.h
and libfoo.so
to end users who will use it.
I figure that paying attention to public and private members would enforce correct coding practices, i.e. making me think about exposing an API to use around my private code.
On the other hand, by having all public members in FooPrivate
, I would have an easier time writing unit tests for it, and also pass it around more easily in my code without having to think about APIs, accessors, etc. Also, the whole thing is private so the end user won't be impacted by this sloppiness, right?
Which would you prefer?
Note that I'm still a beginner at C++ so I could be wrong about my assumptions.
update
Based on the replies, I have settled for continuing to use public/private when appropriate.
The advantage of PIMPL is that I was able to hide the googletest friend test macros in the private header file, without exposing that in the public one, e.g.
#ifdef UNIT_TESTS
#include <gtest/gtest_prod.h>
#endif
class FooPrivate {
public:
...
private:
#ifdef UNIT_TESTS
FRIEND_TEST(FooPrivate, Test1)
#endif
...
};
This way I can write whatever tests I need.
Now whether or not testing private members is a good idea seems like a whole other can of worms.
FooPrivate
, I would have an easier time writing unit tests for it, and also pass it around more easily in my code without having to think about APIs, accessors, etc" This argument is valid for all classes. However, you wouldnt make everything public in every class. – pschill Oct 24 '19 at 7:35