Search code examples
c++static-methodsstatic-classes

How to implement static classes in c++?


I was wanting to implement a simple static class that calculates the pow value of an integer in c++ while practicing. So my codes here:

#pragma once
#ifndef MATH_H
#define MATH_H
static class Math
{
    public:
        static int pow(int,int);
};


#endif /* MATH_H */

And the implemetation of pow function:

#include "Math.h"

int Math::pow(int base, int exp){
    if(exp==1)
        return base;
    else if(exp%2==0)
        return pow(base,exp/2)*pow(base,exp/2);
    else
        return pow(base,exp/2)*pow(base,exp/2)*base;
}

But the cygwin compiler is throwing compilation error:

In file included from Math.cpp:16:0:
Math.h:16:1: error: a storage class can only be specified for objects and functions
 static class Math
 ^~~~~~

Please help me solve my problem.Here are the Microsoft course's official documents from where I have been taught that there are static classes in c++


Solution

  • C++ does not have "static classes" as they formally exist in other languages. You can, however, delete the default constructor (C++ >= 11) or make it private and unimplemented (C++ < 11) which has the same effect of making the type not constructible:

    // C++ >= 11
    class Math
    {
    public:
        Math() = delete;
    };
    
    // C++ < 11
    class Math
    {
    private:
        Math(); // leave unimplemented
    };
    

    With this code, the line Math m; will fail:

    (C++ >= 11) error: use of deleted function 'Math::Math()'

    (C++ < 11) error: 'Math::Math()' is private within this context

    However, "static classes" are mostly an anti-pattern in C++ and free functions should be preferred. (There are some cases where static classes can be useful, particularly when doing template metaprogramming. If you're not doing that then you almost certainly don't need a static class.)

    Consider instead declaring the functions in a namespace:

    namespace math {
        int pow(int, int);
    }