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 (protected
or private
). I also moved the definition of pFoo
after the class. You can't define a variable before it's been declared.
class CFoo
{
public:
static CFoo *pFoo[2];
CFoo(int a);
CFoo *getFoo();
};
CFoo* CFoo::pFoo[2] = {0};
Step 2, pFoo
probably shouldn't be public if you're going to have a getFoo
member function. Let's enforce the interface to the class instead of exposing the internal data.
class CFoo
{
public:
CFoo(int a);
CFoo *getFoo();
private:
static CFoo *pFoo[2];
};
CFoo* CFoo::pFoo[2] = {0};
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 you delete
the 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 by const
pointer to prevent users from accidentally modifying the two static
CFoo objects.
class CFoo
{
public:
CFoo(int a);
const CFoo *getFoo();
private:
static CFoo foos[2];
};
CFoo CFoo::foos[2] = {CFoo(0), CFoo(1)};
The implementation of getFoo
then becomes:
const CFoo * CFoo::getFoo()
{
return &foos[0]; // or &foos[1]
}
IIRC, the static member foos
will be allocated the first time you create a CFoo
object. So, this code...
CFoo bar;
const CFoo *baz = bar.getFoo();
...is safe. The pointer named baz
will point to the static member foos[0]
.
You don’t need the pointers here. In fact, they’re probably not a good idea.
The following code works for me:
#include <iostream>
struct Foo {
static Foo const foos[];
Foo(int i) : i(i) { }
int i;
};
Foo const Foo::foos[2] = { Foo(1), Foo(2) };
using namespace std;
int main() {
cout << Foo::foos[0].i << endl;
}
(Notice that (to keep the demo simple) I’ve made all members public
, which is probably not what you want. It works just as well with private members.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With