views:

141

answers:

3

How do I access a static member in a class with all static methods?

I want to have a group of related functions but also have some important data members initialized before any of these functions are called. I thought a class with only static members would be the way to go. Compiler in VS2008 doesn't like me trying to access "a".

Surely I'm missing something small but still very confused. :P (Even without the invalid access of "a" the constructor isn't called when calling testMethod() from main.

class IPAddressResolver
{
private:

public:
    static int a;
    IPAddressResolver();
    static void TestMethod();
};


IPAddressResolver::IPAddressResolver()
{
    IPAddressResolver::a = 0;
    cout << "Creating IPAddressResolver" << endl;
}

void IPAddressResolver::TestMethod()
{
    cout << "testMethod" << endl;
}
+5  A: 

You need to define your static data member outside of the function, like

class IPAddressResolver
{
private:
    static int a;
    IPAddressResolver();
public:
    static void TestMethod();
};

int IPAddressResolver::a = 0;

void IPAddressResolver::TestMethod()
{
    cout << "testMethod" << endl;
}

Your constructor is not called, since you don't create a new instance of the class. For a static utility class, you don't need instances, so you can omit the constructor altogether. Alternatively, you might want to declare it private to make it explicit that the class shall not be instantiated (see above).

Notes:

  • it is not recommended to use public fields in classes, so I turned a into private,
  • static utility classes are usually stateless, so if you need to have fields within your class, this maybe a sign that the class would better be a Singleton.
Péter Török
Ah. I totally forgot about this. :PBeen using C# for too long.
bobber205
Is there a way to properly initalize members outside of this method? I would like to use a constructor like you can in C#.
bobber205
@bobber, `int IPAddressResolver::a = 0;` does initialize `a` to `0`. If you want a constructor, consider the Singleton approach as I hinted in my notes.
Péter Török
+1  A: 

Somewhere outside of the class definition, you need to define and initialize your static data members associated with that class.

Easiest is just to put

int IPAddressResolver::a = 0;

in your IPAddressResolver.cpp file.

jkerian
+1  A: 

I want to have a group of related functions but also have some important data members initialized before any of these functions are called

Sounds to me like you want a Singleton, not a class with only static members.

Noah Roberts