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.
Asked
Active
Viewed 1,412 times
0
-
1If you initialize something at run time, what is the point to make all functions static? Why don't you make a class object static instead? – vahancho Jul 09 '19 at 13:28
-
It sounds like you want to make a [singleton](https://en.wikipedia.org/wiki/Singleton_pattern) class. – DColt Jul 09 '19 at 13:28
-
4Your `class` is now essentially just a `namespace`. – Jesper Juhl Jul 09 '19 at 13:37
-
2related/maybe dupe: https://stackoverflow.com/questions/7345956/advantages-of-classes-with-only-static-methods-in-c – NathanOliver Jul 09 '19 at 13:44
-
This is really useful and exactly what i was looking for, thanks you – Ovidiu Firescu Jul 09 '19 at 13:50
1 Answers
0
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);
};

Adrien Givry
- 956
- 7
- 18