let say you have to add those private methods
Json::Node AsJson() const;
std::string Serialize(const Json::Node& root) const;
Json::Node Unserialize(const std::string& document) const;
void InitFrom(const Json::Node&);
FORWARD DECLARATION
Assuming Json
is a namespace
, in header you only need forward declaration
namespace Json
{
class Node;
}
instead of
#include <3rdLibrary/Json.hpp>
if Json
is a class and so Json::Node
an inner class, you can't use forward declaration
FREE FUNCTIONS
If the function doesn't require private access (and some other things as no virtual), you may create free functions (in unnamed namespace or static
)
so nothing in header, and in cpp:
#include <3rdLibrary/JsonCpp.hpp>
namespace {
Json::Node AsJson(const MyClass& myclass) {/**/}
std::string Serialize(const MyClass& myclass, const Json::Node& root) {/**/}
Json::Node Unserialize(const MyClass& myclass, const std::string& document) {/**/}
void InitFrom(MyClass& myclass, const Json::Node&){/**/}
}
MyClass::foo()
{
Serialize(*this, AsJson(*this));
/**/
}
PIMPL IDIOM
Pimpl idiom is an other alternative
// header.hpp
class MyClass
{
public:
~MyClass();
MyClass(const MyClass&); // = delete ?
MyClass& operator =(const MyClass&); // = delete ?
MyClass(MyClass&&); // = delete ?
MyClass& operator =(MyClass&&); // = delete ?
// previous public methods.
private:
struct Pimpl;
std::unique_ptr<Pimpl> pimpl;
};
And in source
// MyClass.cpp
struct Pimpl
{
// What you should have done in MyClass
};
MyClass::~MyClass() = default; // which destroys Pimpl and should know Pimpl definition
// that's why it is not in header
ReturnType MyClass::publicMethod(Args args) {return pimpl->publicMethod(args);} // Same for all public methods.
Note: it may be possible to hide with pimpl idiom only some part of implementation
INTERFACE
And finally, similarly to pimpl idiom, you may use interface
// IMyClass.hpp
class IMyClass
{
public:
virtual ~IMyClass() = default;
IMyClass(const IMyClass&); // = delete ?
IMyClass& operator =(const IMyClass&); // = delete ?
IMyClass(IMyClass&&); // = delete ?
IMyClass& operator =(IMyClass&&); // = delete ?
// previous public methods but virtual.
};
std::unique_ptr<IMyClass> makeMyClass(Args);
and implement MyClass
normally (with override
) (its header is only used by its cpp file)
and implement also
std::unique_ptr<IMyClass> makeMyClass(Args args) { return std::make_unique<MyClass>(args); }
Note: it may be possible to expose via interface only some part (to hide only some part of code).