PDA

View Full Version : static class members



space_otter
10th March 2010, 06:13
This is probably a noob question, but...

When I create a static class member of an object type, for example:

class A {
static const A fixed = A();
// should really be immutable, but const not necessary
};

It produces an error "invalid in-class initialization of static data member of non-integral type" so i leave it as:

class A {
static A mFoo;
// should really be immutable, but const not necessary
};
hoping that A will be defined, but apparently it's not. If I leave it like this and try to define it in a function it complains "undefined reference to `A::mFoo'". Examples on the subject use integral data types so it works. I want it to be a fixed object. So how am I supposed to define it?? If I use a pointer and allocate memory the situation doesn't change.

Lykurg
10th March 2010, 06:21
If I use a pointer and allocate memory the situation doesn't change.
It will change, since that is possible (because the compilers does not have to know the size of A). A common case for that is the singleton pattern.
Short and "bad":
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( ) {instance = new Singleton();}
static Singleton* instance;
};

lyuts
10th March 2010, 07:44
Maybe this will help?
In your cpp, outside any function


A* A::mFoo=NULL;


in header


class A;

class A
{
///...
static A* mFoo;
///...
};

space_otter
11th March 2010, 00:07
Ok! I got this.



class A {
public:
static const A* Foo()
{
if(mFoo == 0)
{
mFoo = new A();
mFoo->clear();
}

return mFoo;
}
private:
static A*mFoo;
};

// in cpp
A *A::mFoo= 0;works.

Attempting to use
A *A::mFoo = new A(); to simplify the code caused the most random errors I've seen.