Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Class Data Members and Constructors

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;
}
like image 734
bobber205 Avatar asked Dec 08 '22 03:12

bobber205


1 Answers

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.
like image 123
Péter Török Avatar answered Dec 26 '22 23:12

Péter Török