A class without data in C ++

This may not be a question related to C ++, but more related to object-oriented programming. I am new to this and I doubt my design. I have a Parser class that basically implements a lot of functions for parsing expressions, converting from infix to postfix, etc. I use these Parser functions in the main function. I realized that I do not need data for this class. Therefore, I really do not need an object of this class. Therefore, I turned every function into a class. Something strange in this project. Should I use this as an interface? Any suggestions?

+6
source share
4 answers
  • You need a parser, and you know what you want it to do for you - this is really your β€œinterface”.

  • Your current analyzer implementation does not need member variables, so you do not need a class to implement the interface. So yes, do away with your static methods. According to Kevin, using a namespace with simple old functions (non-static) is a great idea.

  • If you feel that you will need to add a new parser that should support the internal state, then you probably want to define the interface in (1) - a simple old public header file with function declarations inside the namespace of your choice is enough.

+6
source

A class with nothing but static functions seems to me indistinguishable from the namespace. So why not just use a namespace?

+6
source

A way to resolve this issue is how will these functions be used?

1) If all functions are used in one file and do not need to be exported anywhere, then be sure to use static functions. What for? Since you can simply enter them directly into the class body in a .cpp file, and you don’t have to worry about supporting declarations and maintaining parameter alignment. Since when analyzing a C ++ class, all the code inside each function defined inside the body of the class is skipped and then analyzed after all class members are declared, so the functions can see each other and better describe the situation. The compiler will also embed many smaller functions if you declare them directly in this class.

2) If you need to use functions from outside the current .cpp file, then use normal functions. Because later they can be used from anywhere in the world and it is easier to export them by name.

+1
source

It is generally accepted that the utility functions are static, so if the functions of your Parser class do not rely on each other, you can completely make them static. If they rely on each other, and it is possible that the same functions can be performed in a different way, you should consider using an interface

0
source

All Articles