Static class in C++

C++ doesn’t support static classes, but it’s possible to define such declaring all members and functions as static and providing no public constructor.

An static member is only actually referenceable when it is defined (thus, we need to initialize it on the .cpp file). Furthermore, if we’re working with separated files (.cpp and .hpp), one should define them in .cpp file to avoid multiple definitions.

Example:

.hpp:

#include <iostream>
using namespace std;

class myclass {
    myclass();
public:
    static int x;
    static func();
};

.cpp

myclass::int x = 0;
myclass::myclass(){ }
myclass::func(){
    cout << x << endl;
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s