Search code examples
c++staticstatic-classes

C++ class with all members and methods static


I got a program with multiple classes and have one class that has all members and methods static with the following content: two members and two methods to initializate them at start. Also all the members in my static class are public. My question is, if this is a bad practice or if there is any better way to do it? I use the members of this class only in one of the another classes.


Solution

  • Always avoid creating useless symbols.

    If there is no need for a class, create a set of functions in a namespace. If your set of functions needs to manipulate some data, a static class/singleton is the way to go.

    My rule when I design an application is to avoid having stuff that is callable from anywhere.

    The more you restrict yourself (Or the user in the case of a library), the safer your code is (Less bugs due to bad usage).

    If you really need to make a static class, I can suggest you to use a constructor like this one:

    class Foo
    {
        public:
            Foo() = delete;
    };
    

    It avoid confusion between an instanciable class and a completely static class.

    If you like flourishes you can setup something like that:

    #define STATIC_CLASS(class_name) public: class_name() = delete
    
    class Foo
    {
        STATIC_CLASS(Foo);
    };