Archived

This topic is now archived and is closed to further replies.

Accessing static class members in other files

This topic is 5979 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 ?

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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


Share this post


Link to post
Share on other sites