Reputation: 39164
I would like to better understand how to use static field an method in the presence of PIMPL idiom. Consider the following code.
MyClass.h file:
#ifndef MYCLASS
#define MYCLASS
class MyClass{
public:
void method();
static void static_method();
private:
Type field;
static Type *static_field;
}
#endif
MyClass.cpp file:
#include MyClass.h
void MyClass::method(){
/*OK method definition*/
field = new Type(); /*OK field construction*/
}
void MyClass::static_method(){
/*NOT WORKING method declaraion */
static_field = new Type(); /*not working */
}
I have these 2 errors:
I'm not very familiar with pimpl idiom.
So my question is how I achieve static methods and fields declarations to respect the PIMPL idiom and compile it successfully?
What am I doing wrong in this code?
How have I to change my code?
Upvotes: 0
Views: 2714
Reputation: 4925
Indeed, u need to have the definiton
Type* MyClass::static_field = new Type();
at u'r cpp file. this is because this way u tell the compiler at what object file the field should be instantiated, otherwise the compiler has no way to know.
Upvotes: 1
Reputation: 136237
The purpose if pimpl is to eliminate compilation dependencies. The fact that a pimpl class has a private static member is an implementation detail and thus should not be in the header file or in the pimpl class definition.
Put you private statics into the .cc/.cpp file in an unnamed namespace along with the definitions of the member functions of the pimpl class.
Upvotes: 2
Reputation: 91270
static_field
- you have two field
Upvotes: 1