A C++ n00b question. Is it possible to call a private constructor from a static method defined in the cpp? I’d like to keep methods out of the header file if possible — I figure there should be a way to do this. I’m getting an error when attempting this:
“cannot access private member declared in class SomeClass”
/////////////////
// SomeClass.h //
/////////////////
class SomeClass {
public:
static SomeClass SomeMethod();
private:
SomeClass(int i);
}
///////////////////
// SomeClass.cpp //
///////////////////
static SomeClass OSImplementation() {
return SomeClass(0);
};
// calls implementation
SomeClass SomeClass::SomeMethod() {
return OSImplementation();
}
You can make
OSImplementationa friend method.Or you can make
OSImplementationa static method within the class (but that has to be declared in the header).Or, probably the most common way to do this, is to have an internal implementation class, like this:
In your cpp file, you declare
struct SomeClass::Impl.In your constructor, create the
SomeClass::Implinstance. Delete it in the destructor. And implement the copy-constructor and the assignment operator!This is called the PIMPL (pointer to implementation) idiom (Wikipedia, c2.com). It’s used a lot in big projects like Qt.