rules for inclusion in header files when using type in typedef
-
08-07-2019 - |
Question
if I create
typedef double (MyClass::*MemFuncGetter)();
in a header file, do I need to include "MyClass.h" or would forward declaring suffice?
Header file:
#ifndef _TEST_
#define _TEST_
#include "MyClass.h" //do I need this?
//or I can just say class MyClass;
typedef double (MyClass::*MemFuncGetter)();
#endif
What are the linkage rules here?
Solution
You are fine with just the forward declaration of the class:
#ifndef _TEST_
#define _TEST_
class MyClass;
typedef double (MyClass::*MemFuncGetter)();
#endif
But note that by not including the whole class, the compiler has to do extra work to handle the cases when MyClass is a multiple-virtual inheritance mess, since it doesn't know. In some cases this can mean that each function pointer actually takes up to 20 bytes of memory. Whereas if you had defined the whole, each function pointer would only take 4. (Of course the sizes are all compiler-dependant).
OTHER TIPS
You need to have at least a declaration of MyClass
in scope -- a forward declaration at least. Typedef create an alias. It does not create a new type or change the linkage. The linkage will be that of MemFuncGetter
.
Yes forward declraing will enough.
Create file MyClassFwd.h and put there
class MyClass;
typedef double (MyClass::*MemFuncGetter)();
And include forward decl - that will be enough. Don't copy and paste typedef. In your 'MyClass.h' simply include 'MyClassFwd.h'