Reputation: 155
Which is appropriate:
class xyz {
static int xyzOp1() { }
static int xyzOp2() { }
};
OR
namespace xyz {
static int xyzOp1() {}
static int xyzOp2() {}
};
Is there something specific which we can get when we define using class tag in comparision with namespace tag?
Also is there any different in memory management, which we need to worry?
Upvotes: 6
Views: 1812
Reputation: 791709
They mean different things. In a class
context, static
means that methods do not required an object to act on, so are more like free functions. In a namespace
context, it means that the functions have internal linkage so are unique to the translation unit that they are defined in.
In addition, the members of a class
are private by default so, as written, your class functions are only callable from each other. You would need to add a public:
access specifier or make the class
a struct
to change this.
If you need a bunch of free functions and don't need class objects then it's probably more suitable to define them as non-static
functions in a namespace. If they are defined in line in a header file, then they usually need to be declared inline
. This is implied if they are defined in a class
.
Upvotes: 10
Reputation: 5899
The main factor in choosing which method to use would be that your functions themselves may want to operate on private state or utilize private methods, in which case a static class is definitely the better option.
There's a few other nuances, but ultimately a static class will afford you more control in your encapsulation.
Upvotes: 2
Reputation: 127447
Without seeing the body of these functions, I would say that namespaces are more appropriate. With namespaces, you can have using
statements, so that you don't have to fully-qualify the function names when calling them.
The only case in which to use classes is when the static methods have any relationship with objects of the class, e.g. when they need to access private members of instances. From your description, it seems that you won't be creating any instances of xyz, so you shouldn't be using classes here.
From a memory management point of view, there is no difference between these approaches.
Upvotes: 6