I am fairly new to c++, especially in its techniques. My question is, how can I create a static object member of a class itself. What I mean is I declared a static member object inside a class. Example:
CFoo:CFoo *pFoo[2] = {0};
class CFoo
{
public: static CFoo *pFoo[2];
public: CFoo(int a);
public: CFoo *getFoo();
};
Now the problem is, how can I create the pFoo, like I want to create two static object pFoo,
pFoo[0] = new CFoo(0);
pFoo[1] = new CFoo(1);
so that I can use the getFoo method to return one of the pFoo, like,
CFoo *getFoo()
{
return pFoo[0]; //or pFoo(1);
}
Thanks alot guys. Hope my questions are clear.
Thanks again in advance.
-sasayins
Let’s improve your code one step at a time. I’ll explain what I’m doing at each step.
Step 1, this isn’t Java. You don’t need to specify public for every member. Everything after
public:is public until you specify something else (protectedorprivate). I also moved the definition ofpFooafter the class. You can’t define a variable before it’s been declared.Step 2,
pFooprobably shouldn’t be public if you’re going to have agetFoomember function. Let’s enforce the interface to the class instead of exposing the internal data.Step 3, you can return by pointer without bothering to use
new. I’ve written C++ code for many years, and I’d have to look up how youdeletethe memory that was newed for a static member variable. It’s not worth the hassle to figure it out, so let’s just allocate them on the stack. Also, let’s return them byconstpointer to prevent users from accidentally modifying the twostaticCFoo objects.The implementation of
getFoothen becomes:IIRC, the static member
fooswill be allocated the first time you create aCFooobject. So, this code……is safe. The pointer named
bazwill point to the static memberfoos[0].