Short answer
A static class is a class that holds only static members and cannot have objects created from it. C# has this as a keyword, static class. C++ does not, so you get the same effect from a class with only static members, or from a namespace.
The C# version
public static class MathUtil
{
public static int Add(int a, int b)
{
return a + b;
}
}
// MathUtil.Add(2, 3) returns 5.
// new MathUtil() does not compile.
A static class can contain only static members, so every member must be marked static.
The C++ version
C++ has no such keyword, so the usual approach is a class whose default constructor is deleted:
#include <iostream>
class MathUtil {
public:
MathUtil() = delete; // no objects can be created
static int add(int a, int b) {
return a + b;
}
};
int main() {
std::cout << MathUtil::add(2, 3) << "\n"; // prints 5
// MathUtil m; // compile error: the default constructor is deleted
}
Static member functions have no this pointer, so they run without an object. Calling MathUtil::add(2, 3) returns 5.
Using a namespace instead
A namespace is often the simpler choice when you only need functions. Declare the functions inside a namespace, and call them with the namespace name and ::, such as math_util::add(2, 3). Because a namespace has no objects, there is nothing to block, so you do not need the constructor line.
Java’s version
Java does not allow a top-level class to be static. It does let you mark a nested class as static, which means the nested class does not hold a reference to an outer object. That is a different idea from C#’s static class, even though the names are similar.
Which to use in C++
- Use a namespace when you only need functions and constants.
- Use a class with static members when you want a named type for the group, or when some shared data should be
private.
Things to watch
Static members live for the whole run of the program, so anything stored in them persists across calls. Static member functions cannot be virtual, so they do not take part in polymorphism in c.