Reference to class objects
Apr 9, 2009 at 12:34am UTC
Hi all.
Is it possible with generic c++ code to return pointers to all current objects of a certain class within a program?
Apr 9, 2009 at 1:27am UTC
Sort of.
You'd need something like this:
1 2 3 4 5 6 7 8 9 10 11
class A{
static std::set<A *> instances;
A::A(){
A::instances.insert(this );
}
A::~A(){
A::instances.erase(this );
}
};
std::vector<A *> A::instances();
Last edited on Apr 9, 2009 at 1:28am UTC
Apr 9, 2009 at 2:57am UTC
Thanks for your reply.
Could you explain how this works though please :)
I'm still somewhat a beginner and i don't recognize lines 2 and 11.
Thanks for your help.
Apr 9, 2009 at 4:20am UTC
A static member is shared by all instances of a class. Think of it like a global object bound to the type.
Line 2 declares the member, line 11 defines it. Undefined static members produce linker errors.
Topic archived. No new replies allowed.