Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defining bunch of static methods in c++

Tags:

c++

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?

like image 425
harishvk27 Avatar asked Aug 26 '09 06:08

harishvk27


1 Answers

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.

like image 80
CB Bailey Avatar answered Sep 19 '22 17:09

CB Bailey