Accessing static class members in other files

Started by
3 comments, last by PsyCHo puNk 22 years, 8 months ago
Im having problems accessing static data from other files. I define all my class interfaces in headers separate from the implementation in cpp files. Heres an example: Contents of A.h class A { private: friend class B; static int iNum; static void func(void); void somefunc(void); public: A(); virtual ~A(); }; Contents of A.cpp #include "A.h" A::A(){} A::~A(){} void A::func(void) { cout << iNum << endl; } void A::somefunc(void){} Class b also reads the static data (thus referencing it in B.cpp). I think I need to use the extern keyword ?
Advertisement
Nope, don''t need to use extern. static has diferent meanings in different contexts. In the class context it means that among all objects of that class (A) there is only going to exist a single varaible to store iNum (I guess you want that). You need to use public:
Ho hum - opps class B is a friend, so forget the public nonsense above.
1) Are you including the A.h file in B.cpp??
2) Do you have a good reason for making the whole class a friend?
Cos friend anythings generally break OO principals & should be avoided. I''d personally use inline accessor functions (within A) to share private data. If only class B should ask about those data then perhaps your class design is a little off & class B should be nested, or a part of class A.

Sorry I''m rambling & not being much help.

Brad
lol I knew if I posted this SOMEONE would say something about how friend classes are evil . Im doing this because of a situation like this class A is a directdraw encapsulation, class b is a sprite class b needs to access the LPDIRECTDRAW7 member of class A in order to create LPDIRECTDRAWSURFACE7. All of this is internal to a DLL thus preventing people from doing anything screwy since they used the classes through interfaces (like COM). Anyways I knew about what static members do in a class but I am getting the dreaded linker "unresolved external" error that everyone hates.
You have to remember that things in .h files are only declaration.

So for a static member to become a real variable, you must construct it somewhere!

In your .cpp files simply add :

int A::iNum = INIT_VALUE; //INIT_VALUE is whatever you want


! Damn and I remember reading that somewhere too, I just forgot. Well that fixed the problem, thanks!

This topic is closed to new replies.

Advertisement