When I was going through the project on which I am working, I came across a cpp
ID: 658530 • Letter: W
Question
When I was going through the project on which I am working, I came across a cpp file, which has only functions and static variables.I was wondering why they have not put everything into a class! Whenever the inside functions have to be called, the cpp file is included.
Is this a good design? what are the pros and cons of these type of design?
for ex.
//independent.cpp
#include "someclass.h"
static int var1;
static someclass object("hello");
static bool var2;
void foo(const char* dir, const char* filename){
...
}
somefile.cpp
#include "independent.cpp"
class sample{
public:
void caller(){
foo("c:", "file.txt");
}
}
Explanation / Answer
What are the pros and cons of these type of design?
Pros: easy to write, easy to read, easy to call.
Cons: naming conflicts, risk of global variables, difficult to override.
I was wondering why they have not put everything into a class!
If your functions don't need a context (e.g. utility functions), you're going to have difficulties finding a meaningful place for them in a class. As much as classes are a very useful way to organise code and instances, there are scenarios where they're not worth the hassle.
You could also argue it's not much of an effort to put it in a class. That's a valid point, but the author(s) didn't see any added value to it.
Is this a good design?
I 100% agree with Emilio Garavaglia's take on that: Whether it is a good or a bad design depends on the context. It's not wrong to do it this way, but it may be infeasible in the scope of some projects.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.