Inline Function in Namespace Scope and Static Function in Class Scope - c++

Is there any semantic difference between the two in the title?
For example, I can write,
class Hi{
public:
static void Print(){
printf("hi\n");
}
};
but also,
namespace Hi{
inline void Print(){
printf("hi\n");
}
}
I'm of course assuming both of these definitions are in the header. Is it just a matter of style?

A main difference is that namespaces can be extended, while classes can be inherited. This difference was important for "enum wrappers" in C++03. Some people strongly favored wrapping enums in classes, and others strongly favored wrapping them in namespaces, while perhaps most didn't care and didn't wrap.
Namespaces support argument dependent lookup, while classes don't (except for calls of friend functions defined in class definitions, and then it's really namespace ADL kicking in).
Classes support access control (public, protected, private) while namespaces don't. With namespaces the technique corresponding to private access is a nested namespace called detail or impl or some such. But this is just convention, not something the compiler can check and enforce.
I guess that since the above is what occurred to me first, it's probably the most relevant.
Worth noting: libraries that uses classes as a kind of faux namespace mechanism do exist (in particular I ran into an XML parser library of that kind), but they are very rare, and I doubt that any new libraries do this except for possible the above mentioned enum wrapping, which however was made less important by the scoped enums of C++11.

Although the class in your first example serves as a makeshift namespace, the differences are not limited to style.
For example, static member functions get access to private members of the class, such as other static functions of the same class, private types defined inside the class, and private static variables defined inside the class.
You can emulate a lot of this behavior with namespaces and static non-member functions / variables defined in the scope of a translation unit. However, the emulation would not be complete when non-static members of the class need to share access to private members with static member functions. In this case you would need to provide additional functionality to expose private members to non-members, while member functions would get it for free.
Here is an example based on your code:
class Hi{
private:
// This static member variable is defined in a cpp file
static int count;
public:
Hi() { // Let's pretend concurrency does not exist
count++;
}
static void Print(){
printf("You said Hi %d times\n", count);
}
};
If you wanted to emulate the above behavior with namespaces, you would need to declare your Hi::Print a friend of a class, or provide a public function to get the current value of count.

Related

Is it bad practice to have a class that requires no objects to be created? [duplicate]

Let's say I have, or am going to write, a set of related functions. Let's say they're math-related. Organizationally, should I:
Write these functions and put them in my MyMath namespace and refer to them via MyMath::XYZ()
Create a class called MyMath and make these methods static and refer to the similarly MyMath::XYZ()
Why would I choose one over the other as a means of organizing my software?
By default, use namespaced functions.
Classes are to build objects, not to replace namespaces.
In Object Oriented code
Scott Meyers wrote a whole Item for his Effective C++ book on this topic, "Prefer non-member non-friend functions to member functions". I found an online reference to this principle in an article from Herb Sutter: http://www.gotw.ca/gotw/084.htm
The important thing to know is that: In C++, functions that are in the same namespace as a class is, and that have that class as a parameter, belong to that class' interface (because ADL will search those functions when resolving function calls).
For example:
let's say you have a namespace N
let's say you have a class C, declared in namespace N (in other words, its full name is N::C)
let's say you have a function F, declared in namespace N (in other words, its full name is N::F)
let's say that function F has, among its parameters, a parameter of type C
... Then N::F is part of N::C's public interface.
Namespaced functions, unless declared "friend," have no access to the class's internals, whereas static methods have the right to access the class's internals.
This means, for example, that when maintaining your class, if you need to change your class' internals, you will need to search for side effects in all its methods, including the static ones.
Extension I
Adding code to a class' interface.
In C#, you can add methods to a class even if you have no access to it. But in C++, this is impossible.
But, still in C++, you can still add a namespaced function, even to a class someone wrote for you.
See from the other side, this is important when designing your code, because by putting your functions in a namespace, you will authorize your users to increase/complete the class' interface.
Extension II
A side-effect of the previous point, it is impossible to declare static methods in multiple headers. Every method must be declared in the same class.
For namespaces, functions from the same namespace can be declared in multiple headers (the almost-standard swap function is the best example of that).
Extension III
The basic coolness of a namespace is that in some code, you can avoid mentioning it, if you use the keyword using:
#include <string>
#include <vector>
// Etc.
{
using namespace std ;
// Now, everything from std is accessible without qualification
string s ; // Ok
vector v ; // Ok
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
And you can even limit the "pollution" to one class:
#include <string>
#include <vector>
{
using std::string ;
string s ; // Ok
vector v ; // COMPILATION ERROR
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
This "pattern" is mandatory for the proper use of the almost-standard swap idiom.
And this is impossible to do with static methods in classes.
So, C++ namespaces have their own semantics.
But it goes further, as you can combine namespaces in a way similar to inheritance.
For example, if you have a namespace A with a function AAA, a namespace B with a function BBB, you can declare a namespace C, and bring AAA and BBB in this namespace with the keyword using.
You can even bring the full content of a namespace inside another, with using namespace, as shown with namespace D!
namespace A
{
void AAA();
void AAA2();
}
namespace B
{
void BBB();
}
namespace C
{
using A::AAA;
using B::BBB;
}
namespace D
{
using namespace A;
using namespace B;
}
void foo()
{
C::AAA();
// C::AAA2(); // ERROR, won't compile
C::BBB();
}
void bar()
{
D::AAA();
D::AAA2();
D::BBB();
}
Conclusion
Namespaces are for namespaces.
Classes are for classes.
C++ was designed so each concept is different, and is used differently, in different cases, as a solution to different problems.
Don't use classes when you need namespaces.
And in your case, you need namespaces.
There are a lot of people who would disagree with me, but this is how I see it:
A class is essentially a definition of a certain kind of object. Static methods should define operations that are intimately tied to that object definition.
If you are just going to have a group of related functions not associated with an underlying object or definition of a kind of object, then I would say go with a namespace only. Just for me, conceptually, this is a lot more sensible.
For instance, in your case, ask yourself, "What is a MyMath?" If MyMath does not define a kind of object, then I would say: don't make it a class.
But like I said, I know there are plenty of folks who would (even vehemently) disagree with me on this (in particular, Java and C# developers).
If you need static data, use static methods.
If they're template functions and you'd like to be able to specify a set of template parameters for all functions together then use static methods in a template class.
Otherwise, use namespaced functions.
In response to the comments: yes, static methods and static data tend to be over-used. That's why I offered only two, related scenarios where I think they can be helpful. In the OP's specific example (a set of math routines), if he wanted the ability to specify parameters - say, a core data type and output precision - that would be applied to all routines, he might do something like:
template<typename T, int decimalPlaces>
class MyMath
{
// routines operate on datatype T, preserving at least decimalPlaces precision
};
// math routines for manufacturing calculations
typedef MyMath<double, 4> CAMMath;
// math routines for on-screen displays
typedef MyMath<float, 2> PreviewMath;
If you don't need that, then by all means use a namespace.
You should use a namespace, because a namespace has the many advantages over a class:
You don't have to define everything in the same header
You don't need to expose all your implementation in the header
You can't using a class member; you can using a namespace member
You can't using class, though using namespace is not all that often a good idea
Using a class implies that there is some object to be created when there really is none
Static members are, in my opinion, very very overused. They aren't a real necessity in most cases. Static members functions are probably better off as file-scope functions, and static data members are just global objects with a better, undeserved reputation.
I would prefer namespaces, that way you can have private data in an anonymous namespace in the implementation file (so it doesn't have to show up in the header at all as opposed to private members). Another benefit is that by using your namespace the clients of the methods can opt out of specifying MyMath::
I want to summarize and add to other answers. Also, my perspective is in the world of header-only.
Namespaces
Pros:
simple solution for naming hierarchies
they carry no semantics, so it is simpler to read
can live in different files (headers)
can be extended
ADL
shortcut can be defined (using).
Plays well with operator overload
Can be used for branding (you can design your code and put a namespace over it without much though)
Cons:
everything is public
private things need unnamed namespace so it is not explicit
ADL (yes, some people despise ADL)
can be extended (this can be a bad thing, specially in combination with ADL, semantics of existing code can change by extending the namespace)
functions need to be defined (or declared) in order of use
Classes with static methods
Pros:
can have private components (function, variables) and they are explicitly marked.
classes can be friended
can be type-parametrized (templates)
can be template parameters themselves
can be instantiated
can be passed to functions (static functions behave like non-static method by default).
it is easier to find patterns and go from groups of independent functions and convert them to a proper class (eventually with non static members)
dependencies among classes is well defined
functions (the static method) can be defined in any order
Cons:
No ADL
cannot be extended
needs the keyword static everywhere (opportunity to make fun of the language)
an overkill to solve the naming problem alone. Difficult to read in that case.
the functions (static methods) always need qualification (myclassspace::fun). There is no way to declare shortcuts (using).
almost useless for operator overload, needs complicated friend mechanism for that.
can not be used for branding.
you need to remember end it with ; :)
In summary, classes with static methods are better units of code and allow more meta programming, and except for ADL and some syntactic quirks, can replicate all the features of namespaces, but they can be an overkill sometimes.
Companies, such as Bloomberg, prefer classes over namespaces.
If you don’t like ADL or operator overload, classes with static methods is the way to go.
IMO, it would be nice if namespace and classes are integrated to become two sides of the same coin.
For example identify a namespace in the language as a class were the methods are static by default.
And then be able to use them as template parameters.
I wouldn't be sure what to do with ADL (may be it could be restricted to symbolic operators functions alone, e.g. operatorX, which was the original motivation for operator overload and ADL in the first place)
Why would I choose one over the other as a means of organizing my software?
If you use namespaces, you will frequently hit a language defect that functions which call each other must be listed in a specific order, because C++ can't see definitions further down in the file.
If you use classes, this defect does not occur.
It can be easier and cleaner to wrap implementation functions in a class than to maintain declarations for them all or put them in an unnatural order to make it compile.
One more reason to use class - Option to make use of access specifiers. You can then possibly break your public static method into smaller private methods. Public method can call multiple private methods.
Both namespace and class method have their uses. Namespace have the ability to be spread across files however that is a weakness if you need to enforce all related code to go in one file. As mentioned above class also allows you to create private static members in the class. You can have it in the anonymous namespace of the implementation file however it is still a bigger scope than having them inside the class.

Differences between an abstract class with static functions and regular functions in a namespace? [duplicate]

Let's say I have, or am going to write, a set of related functions. Let's say they're math-related. Organizationally, should I:
Write these functions and put them in my MyMath namespace and refer to them via MyMath::XYZ()
Create a class called MyMath and make these methods static and refer to the similarly MyMath::XYZ()
Why would I choose one over the other as a means of organizing my software?
By default, use namespaced functions.
Classes are to build objects, not to replace namespaces.
In Object Oriented code
Scott Meyers wrote a whole Item for his Effective C++ book on this topic, "Prefer non-member non-friend functions to member functions". I found an online reference to this principle in an article from Herb Sutter: http://www.gotw.ca/gotw/084.htm
The important thing to know is that: In C++, functions that are in the same namespace as a class is, and that have that class as a parameter, belong to that class' interface (because ADL will search those functions when resolving function calls).
For example:
let's say you have a namespace N
let's say you have a class C, declared in namespace N (in other words, its full name is N::C)
let's say you have a function F, declared in namespace N (in other words, its full name is N::F)
let's say that function F has, among its parameters, a parameter of type C
... Then N::F is part of N::C's public interface.
Namespaced functions, unless declared "friend," have no access to the class's internals, whereas static methods have the right to access the class's internals.
This means, for example, that when maintaining your class, if you need to change your class' internals, you will need to search for side effects in all its methods, including the static ones.
Extension I
Adding code to a class' interface.
In C#, you can add methods to a class even if you have no access to it. But in C++, this is impossible.
But, still in C++, you can still add a namespaced function, even to a class someone wrote for you.
See from the other side, this is important when designing your code, because by putting your functions in a namespace, you will authorize your users to increase/complete the class' interface.
Extension II
A side-effect of the previous point, it is impossible to declare static methods in multiple headers. Every method must be declared in the same class.
For namespaces, functions from the same namespace can be declared in multiple headers (the almost-standard swap function is the best example of that).
Extension III
The basic coolness of a namespace is that in some code, you can avoid mentioning it, if you use the keyword using:
#include <string>
#include <vector>
// Etc.
{
using namespace std ;
// Now, everything from std is accessible without qualification
string s ; // Ok
vector v ; // Ok
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
And you can even limit the "pollution" to one class:
#include <string>
#include <vector>
{
using std::string ;
string s ; // Ok
vector v ; // COMPILATION ERROR
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
This "pattern" is mandatory for the proper use of the almost-standard swap idiom.
And this is impossible to do with static methods in classes.
So, C++ namespaces have their own semantics.
But it goes further, as you can combine namespaces in a way similar to inheritance.
For example, if you have a namespace A with a function AAA, a namespace B with a function BBB, you can declare a namespace C, and bring AAA and BBB in this namespace with the keyword using.
You can even bring the full content of a namespace inside another, with using namespace, as shown with namespace D!
namespace A
{
void AAA();
void AAA2();
}
namespace B
{
void BBB();
}
namespace C
{
using A::AAA;
using B::BBB;
}
namespace D
{
using namespace A;
using namespace B;
}
void foo()
{
C::AAA();
// C::AAA2(); // ERROR, won't compile
C::BBB();
}
void bar()
{
D::AAA();
D::AAA2();
D::BBB();
}
Conclusion
Namespaces are for namespaces.
Classes are for classes.
C++ was designed so each concept is different, and is used differently, in different cases, as a solution to different problems.
Don't use classes when you need namespaces.
And in your case, you need namespaces.
There are a lot of people who would disagree with me, but this is how I see it:
A class is essentially a definition of a certain kind of object. Static methods should define operations that are intimately tied to that object definition.
If you are just going to have a group of related functions not associated with an underlying object or definition of a kind of object, then I would say go with a namespace only. Just for me, conceptually, this is a lot more sensible.
For instance, in your case, ask yourself, "What is a MyMath?" If MyMath does not define a kind of object, then I would say: don't make it a class.
But like I said, I know there are plenty of folks who would (even vehemently) disagree with me on this (in particular, Java and C# developers).
If you need static data, use static methods.
If they're template functions and you'd like to be able to specify a set of template parameters for all functions together then use static methods in a template class.
Otherwise, use namespaced functions.
In response to the comments: yes, static methods and static data tend to be over-used. That's why I offered only two, related scenarios where I think they can be helpful. In the OP's specific example (a set of math routines), if he wanted the ability to specify parameters - say, a core data type and output precision - that would be applied to all routines, he might do something like:
template<typename T, int decimalPlaces>
class MyMath
{
// routines operate on datatype T, preserving at least decimalPlaces precision
};
// math routines for manufacturing calculations
typedef MyMath<double, 4> CAMMath;
// math routines for on-screen displays
typedef MyMath<float, 2> PreviewMath;
If you don't need that, then by all means use a namespace.
You should use a namespace, because a namespace has the many advantages over a class:
You don't have to define everything in the same header
You don't need to expose all your implementation in the header
You can't using a class member; you can using a namespace member
You can't using class, though using namespace is not all that often a good idea
Using a class implies that there is some object to be created when there really is none
Static members are, in my opinion, very very overused. They aren't a real necessity in most cases. Static members functions are probably better off as file-scope functions, and static data members are just global objects with a better, undeserved reputation.
I would prefer namespaces, that way you can have private data in an anonymous namespace in the implementation file (so it doesn't have to show up in the header at all as opposed to private members). Another benefit is that by using your namespace the clients of the methods can opt out of specifying MyMath::
I want to summarize and add to other answers. Also, my perspective is in the world of header-only.
Namespaces
Pros:
simple solution for naming hierarchies
they carry no semantics, so it is simpler to read
can live in different files (headers)
can be extended
ADL
shortcut can be defined (using).
Plays well with operator overload
Can be used for branding (you can design your code and put a namespace over it without much though)
Cons:
everything is public
private things need unnamed namespace so it is not explicit
ADL (yes, some people despise ADL)
can be extended (this can be a bad thing, specially in combination with ADL, semantics of existing code can change by extending the namespace)
functions need to be defined (or declared) in order of use
Classes with static methods
Pros:
can have private components (function, variables) and they are explicitly marked.
classes can be friended
can be type-parametrized (templates)
can be template parameters themselves
can be instantiated
can be passed to functions (static functions behave like non-static method by default).
it is easier to find patterns and go from groups of independent functions and convert them to a proper class (eventually with non static members)
dependencies among classes is well defined
functions (the static method) can be defined in any order
Cons:
No ADL
cannot be extended
needs the keyword static everywhere (opportunity to make fun of the language)
an overkill to solve the naming problem alone. Difficult to read in that case.
the functions (static methods) always need qualification (myclassspace::fun). There is no way to declare shortcuts (using).
almost useless for operator overload, needs complicated friend mechanism for that.
can not be used for branding.
you need to remember end it with ; :)
In summary, classes with static methods are better units of code and allow more meta programming, and except for ADL and some syntactic quirks, can replicate all the features of namespaces, but they can be an overkill sometimes.
Companies, such as Bloomberg, prefer classes over namespaces.
If you don’t like ADL or operator overload, classes with static methods is the way to go.
IMO, it would be nice if namespace and classes are integrated to become two sides of the same coin.
For example identify a namespace in the language as a class were the methods are static by default.
And then be able to use them as template parameters.
I wouldn't be sure what to do with ADL (may be it could be restricted to symbolic operators functions alone, e.g. operatorX, which was the original motivation for operator overload and ADL in the first place)
Why would I choose one over the other as a means of organizing my software?
If you use namespaces, you will frequently hit a language defect that functions which call each other must be listed in a specific order, because C++ can't see definitions further down in the file.
If you use classes, this defect does not occur.
It can be easier and cleaner to wrap implementation functions in a class than to maintain declarations for them all or put them in an unnatural order to make it compile.
One more reason to use class - Option to make use of access specifiers. You can then possibly break your public static method into smaller private methods. Public method can call multiple private methods.
Both namespace and class method have their uses. Namespace have the ability to be spread across files however that is a weakness if you need to enforce all related code to go in one file. As mentioned above class also allows you to create private static members in the class. You can have it in the anonymous namespace of the implementation file however it is still a bigger scope than having them inside the class.

Static functions in class or namespace [duplicate]

Let's say I have, or am going to write, a set of related functions. Let's say they're math-related. Organizationally, should I:
Write these functions and put them in my MyMath namespace and refer to them via MyMath::XYZ()
Create a class called MyMath and make these methods static and refer to the similarly MyMath::XYZ()
Why would I choose one over the other as a means of organizing my software?
By default, use namespaced functions.
Classes are to build objects, not to replace namespaces.
In Object Oriented code
Scott Meyers wrote a whole Item for his Effective C++ book on this topic, "Prefer non-member non-friend functions to member functions". I found an online reference to this principle in an article from Herb Sutter: http://www.gotw.ca/gotw/084.htm
The important thing to know is that: In C++, functions that are in the same namespace as a class is, and that have that class as a parameter, belong to that class' interface (because ADL will search those functions when resolving function calls).
For example:
let's say you have a namespace N
let's say you have a class C, declared in namespace N (in other words, its full name is N::C)
let's say you have a function F, declared in namespace N (in other words, its full name is N::F)
let's say that function F has, among its parameters, a parameter of type C
... Then N::F is part of N::C's public interface.
Namespaced functions, unless declared "friend," have no access to the class's internals, whereas static methods have the right to access the class's internals.
This means, for example, that when maintaining your class, if you need to change your class' internals, you will need to search for side effects in all its methods, including the static ones.
Extension I
Adding code to a class' interface.
In C#, you can add methods to a class even if you have no access to it. But in C++, this is impossible.
But, still in C++, you can still add a namespaced function, even to a class someone wrote for you.
See from the other side, this is important when designing your code, because by putting your functions in a namespace, you will authorize your users to increase/complete the class' interface.
Extension II
A side-effect of the previous point, it is impossible to declare static methods in multiple headers. Every method must be declared in the same class.
For namespaces, functions from the same namespace can be declared in multiple headers (the almost-standard swap function is the best example of that).
Extension III
The basic coolness of a namespace is that in some code, you can avoid mentioning it, if you use the keyword using:
#include <string>
#include <vector>
// Etc.
{
using namespace std ;
// Now, everything from std is accessible without qualification
string s ; // Ok
vector v ; // Ok
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
And you can even limit the "pollution" to one class:
#include <string>
#include <vector>
{
using std::string ;
string s ; // Ok
vector v ; // COMPILATION ERROR
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
This "pattern" is mandatory for the proper use of the almost-standard swap idiom.
And this is impossible to do with static methods in classes.
So, C++ namespaces have their own semantics.
But it goes further, as you can combine namespaces in a way similar to inheritance.
For example, if you have a namespace A with a function AAA, a namespace B with a function BBB, you can declare a namespace C, and bring AAA and BBB in this namespace with the keyword using.
You can even bring the full content of a namespace inside another, with using namespace, as shown with namespace D!
namespace A
{
void AAA();
void AAA2();
}
namespace B
{
void BBB();
}
namespace C
{
using A::AAA;
using B::BBB;
}
namespace D
{
using namespace A;
using namespace B;
}
void foo()
{
C::AAA();
// C::AAA2(); // ERROR, won't compile
C::BBB();
}
void bar()
{
D::AAA();
D::AAA2();
D::BBB();
}
Conclusion
Namespaces are for namespaces.
Classes are for classes.
C++ was designed so each concept is different, and is used differently, in different cases, as a solution to different problems.
Don't use classes when you need namespaces.
And in your case, you need namespaces.
There are a lot of people who would disagree with me, but this is how I see it:
A class is essentially a definition of a certain kind of object. Static methods should define operations that are intimately tied to that object definition.
If you are just going to have a group of related functions not associated with an underlying object or definition of a kind of object, then I would say go with a namespace only. Just for me, conceptually, this is a lot more sensible.
For instance, in your case, ask yourself, "What is a MyMath?" If MyMath does not define a kind of object, then I would say: don't make it a class.
But like I said, I know there are plenty of folks who would (even vehemently) disagree with me on this (in particular, Java and C# developers).
If you need static data, use static methods.
If they're template functions and you'd like to be able to specify a set of template parameters for all functions together then use static methods in a template class.
Otherwise, use namespaced functions.
In response to the comments: yes, static methods and static data tend to be over-used. That's why I offered only two, related scenarios where I think they can be helpful. In the OP's specific example (a set of math routines), if he wanted the ability to specify parameters - say, a core data type and output precision - that would be applied to all routines, he might do something like:
template<typename T, int decimalPlaces>
class MyMath
{
// routines operate on datatype T, preserving at least decimalPlaces precision
};
// math routines for manufacturing calculations
typedef MyMath<double, 4> CAMMath;
// math routines for on-screen displays
typedef MyMath<float, 2> PreviewMath;
If you don't need that, then by all means use a namespace.
You should use a namespace, because a namespace has the many advantages over a class:
You don't have to define everything in the same header
You don't need to expose all your implementation in the header
You can't using a class member; you can using a namespace member
You can't using class, though using namespace is not all that often a good idea
Using a class implies that there is some object to be created when there really is none
Static members are, in my opinion, very very overused. They aren't a real necessity in most cases. Static members functions are probably better off as file-scope functions, and static data members are just global objects with a better, undeserved reputation.
I would prefer namespaces, that way you can have private data in an anonymous namespace in the implementation file (so it doesn't have to show up in the header at all as opposed to private members). Another benefit is that by using your namespace the clients of the methods can opt out of specifying MyMath::
I want to summarize and add to other answers. Also, my perspective is in the world of header-only.
Namespaces
Pros:
simple solution for naming hierarchies
they carry no semantics, so it is simpler to read
can live in different files (headers)
can be extended
ADL
shortcut can be defined (using).
Plays well with operator overload
Can be used for branding (you can design your code and put a namespace over it without much though)
Cons:
everything is public
private things need unnamed namespace so it is not explicit
ADL (yes, some people despise ADL)
can be extended (this can be a bad thing, specially in combination with ADL, semantics of existing code can change by extending the namespace)
functions need to be defined (or declared) in order of use
Classes with static methods
Pros:
can have private components (function, variables) and they are explicitly marked.
classes can be friended
can be type-parametrized (templates)
can be template parameters themselves
can be instantiated
can be passed to functions (static functions behave like non-static method by default).
it is easier to find patterns and go from groups of independent functions and convert them to a proper class (eventually with non static members)
dependencies among classes is well defined
functions (the static method) can be defined in any order
Cons:
No ADL
cannot be extended
needs the keyword static everywhere (opportunity to make fun of the language)
an overkill to solve the naming problem alone. Difficult to read in that case.
the functions (static methods) always need qualification (myclassspace::fun). There is no way to declare shortcuts (using).
almost useless for operator overload, needs complicated friend mechanism for that.
can not be used for branding.
you need to remember end it with ; :)
In summary, classes with static methods are better units of code and allow more meta programming, and except for ADL and some syntactic quirks, can replicate all the features of namespaces, but they can be an overkill sometimes.
Companies, such as Bloomberg, prefer classes over namespaces.
If you don’t like ADL or operator overload, classes with static methods is the way to go.
IMO, it would be nice if namespace and classes are integrated to become two sides of the same coin.
For example identify a namespace in the language as a class were the methods are static by default.
And then be able to use them as template parameters.
I wouldn't be sure what to do with ADL (may be it could be restricted to symbolic operators functions alone, e.g. operatorX, which was the original motivation for operator overload and ADL in the first place)
Why would I choose one over the other as a means of organizing my software?
If you use namespaces, you will frequently hit a language defect that functions which call each other must be listed in a specific order, because C++ can't see definitions further down in the file.
If you use classes, this defect does not occur.
It can be easier and cleaner to wrap implementation functions in a class than to maintain declarations for them all or put them in an unnatural order to make it compile.
One more reason to use class - Option to make use of access specifiers. You can then possibly break your public static method into smaller private methods. Public method can call multiple private methods.
Both namespace and class method have their uses. Namespace have the ability to be spread across files however that is a weakness if you need to enforce all related code to go in one file. As mentioned above class also allows you to create private static members in the class. You can have it in the anonymous namespace of the implementation file however it is still a bigger scope than having them inside the class.

C++: Why must private functions be declared?

Why do classes in C++ have to declare their private functions? Has it actual technical reasons (what is its role at compile time) or is it simply for consistency's sake?
I asked why private functions had to be declared at all, as they don't add anything (neither object size nor vtable entry) for other translation units to know
If you think about it, this is similar to declaring some functions static in a file. It's not visible from the outside, but it is important for the compiler itself. The compiler wants to know the signature of the function before it can use it. That's why you declare functions in the first place. Remember that C++ compilers are one pass, which means everything has to be declared before it is used.1
From the programmer's point of view, declaring private functions is still not completely useless. Imagine 2 classes, one of which is the friend of the other. The friendzoned class2 would need to know how the privates of that class look like, (This discussion is getting weird) otherwise they can't use it.
As to why exactly C++ was designed in this way, I would first say there is the historical reason: the fact that you can't slice a struct in C, was adopted by C++ so you can't slice a class (and adopted by other languages branched from C++, too). I'd also guess that it's about simplicity: Imagine how difficult it would be to devise a method of compilation in which you can split the class among different header files, let your source files know about it, and prevent others from adding stuff to your class.
A final note is that, private functions can affect vtable size. That is, if they are virtual.
1 Actually not entirely. If you have inline functions in the class, they can refer to functions later defined in the same class. But probably the idea started from single pass and this exception later added to it.
2 It's inlined member functions in particular.
You have to declare all members in the definition of the class itself so that the compiler knows which functions are allowed to be members. Otherwise, a second programmer could (accidentally?) come along and add members, make mistakes, and violate your object's guarantees, causing undefined behavior and/or random crashes.
There's a combination of concerns, but:
C++ doesn't let you re-open a class to declare new members in it after its initial definition.
C++ doesn't let you have different definitions of a class in different translation units that combine to form a program.
Therefore:
Any private member functions that the .cpp file wants declared in the class need to be defined in the .h file, which every user of the class sees too.
From the POV of practical binary compatibility: as David says in a comment, private virtual functions affect the size and layout of the vtable of this class and any classes that use it as a base. So the compiler needs to know about them even when compiling code that can't call them.
Could C++ have been invented differently, to allow the .cpp file to reopen the class and add certain kinds of additional member functions, with the implementation required to arrange that this doesn't break binary compatibility? Could the one definition rule be relaxed, to allow definitions that differ in certain ways? For example, static member functions and non-virtual non-static member functions.
Probably yes to both. I don't think there's any technical obstacle, although the current ODR is very strict about what makes a definition "different" (and hence is very generous to implementations in allowing binary incompatibilities between very similar-looking definitions). I think the text to introduce this kind of exception to the rule would be complex.
Ultimately it might come down to, "the designers wanted it that way", or it might be that someone tried it and encountered an obstacle that I haven't thought of.
The access level does not affect visibility. Private functions are visible to external code and may be selected by overload resolution (which would then result in an access violoation error):
class A {
void F(int i) {}
public:
void F(unsigned i) {}
};
int main() {
A a;
a.F(1); // error, void A::F(int) is private
}
Imagine the confusion when this works:
class A {
public:
void F(unsigned i) {}
};
int main() {
A a;
a.F(1);
}
// add private F overload to A
void A::F(int i) {}
But changing it to the first code causes overload resolution to select a different function. And what about the following example?
class A {
public:
void F(unsigned i) {}
};
// add private F overload to A
void A::F(int i) {}
int main() {
A a;
a.F(1);
}
Or here's another example of this going wrong:
// A.h
class A {
public:
void g() { f(1); }
void f(unsigned);
};
// A_private_interface.h
class A;
void A::f(int);
// A.cpp
#include "A_private_interface.h"
#include "A.h"
void A::f(int) {}
void A::f(unsigned) {}
// main.cpp
#include "A.h"
int main() {
A().g();
}
One reason is that in C++ friends can access your privates. For friends to access them, friends have to know about them.
Private members of a class are still members of the class, so they must be declared, as the implementation of other public members might depend on that private method. Declaring them will allow the compiler to understand a call to that function as a member function call.
If you have a method that only is used int the .cpp file and does not depend on direct access to other private members of the class, consider moving it to an anonymous namespace. Then, it does not need to be declared in the header file.
There are a couple of reason on why private functions must be declared.
First Compile Time Error Checks
the point of access modifiers is to catch certain classes (no pun intended) of programming errors at compile time. Private functions are functions that, if someone called them from outside the class, that would be a bug, and you want to know about it as early as possible.
Second Casting and Inheritance
Taken from the C++ standard:
3 [ Note: A member of a private base class might be inaccessible as an inherited member name, but accessible directly. Because of the rules on pointer conversions (4.10) and explicit casts (5.4), a conversion from a pointer to a derived class to a pointer to an inaccessible base class might be ill-formed if an implicit conversion is used, but well-formed if an explicit cast is used.
3rd Friends
Friends show each other there privates. A private method can be call by another class that is a friend.
4th General Sanity and Good Design
Ever worked on a project with another 100 developers. Having a standard and a general set of rule helps maintain maintainable. declaring something private has a specific meaning to everyone else in the group.
Also this flows into good OO design principles. What to expose and what not

Namespace + functions versus static methods on a class

Let's say I have, or am going to write, a set of related functions. Let's say they're math-related. Organizationally, should I:
Write these functions and put them in my MyMath namespace and refer to them via MyMath::XYZ()
Create a class called MyMath and make these methods static and refer to the similarly MyMath::XYZ()
Why would I choose one over the other as a means of organizing my software?
By default, use namespaced functions.
Classes are to build objects, not to replace namespaces.
In Object Oriented code
Scott Meyers wrote a whole Item for his Effective C++ book on this topic, "Prefer non-member non-friend functions to member functions". I found an online reference to this principle in an article from Herb Sutter: http://www.gotw.ca/gotw/084.htm
The important thing to know is that: In C++, functions that are in the same namespace as a class is, and that have that class as a parameter, belong to that class' interface (because ADL will search those functions when resolving function calls).
For example:
let's say you have a namespace N
let's say you have a class C, declared in namespace N (in other words, its full name is N::C)
let's say you have a function F, declared in namespace N (in other words, its full name is N::F)
let's say that function F has, among its parameters, a parameter of type C
... Then N::F is part of N::C's public interface.
Namespaced functions, unless declared "friend," have no access to the class's internals, whereas static methods have the right to access the class's internals.
This means, for example, that when maintaining your class, if you need to change your class' internals, you will need to search for side effects in all its methods, including the static ones.
Extension I
Adding code to a class' interface.
In C#, you can add methods to a class even if you have no access to it. But in C++, this is impossible.
But, still in C++, you can still add a namespaced function, even to a class someone wrote for you.
See from the other side, this is important when designing your code, because by putting your functions in a namespace, you will authorize your users to increase/complete the class' interface.
Extension II
A side-effect of the previous point, it is impossible to declare static methods in multiple headers. Every method must be declared in the same class.
For namespaces, functions from the same namespace can be declared in multiple headers (the almost-standard swap function is the best example of that).
Extension III
The basic coolness of a namespace is that in some code, you can avoid mentioning it, if you use the keyword using:
#include <string>
#include <vector>
// Etc.
{
using namespace std ;
// Now, everything from std is accessible without qualification
string s ; // Ok
vector v ; // Ok
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
And you can even limit the "pollution" to one class:
#include <string>
#include <vector>
{
using std::string ;
string s ; // Ok
vector v ; // COMPILATION ERROR
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
This "pattern" is mandatory for the proper use of the almost-standard swap idiom.
And this is impossible to do with static methods in classes.
So, C++ namespaces have their own semantics.
But it goes further, as you can combine namespaces in a way similar to inheritance.
For example, if you have a namespace A with a function AAA, a namespace B with a function BBB, you can declare a namespace C, and bring AAA and BBB in this namespace with the keyword using.
You can even bring the full content of a namespace inside another, with using namespace, as shown with namespace D!
namespace A
{
void AAA();
void AAA2();
}
namespace B
{
void BBB();
}
namespace C
{
using A::AAA;
using B::BBB;
}
namespace D
{
using namespace A;
using namespace B;
}
void foo()
{
C::AAA();
// C::AAA2(); // ERROR, won't compile
C::BBB();
}
void bar()
{
D::AAA();
D::AAA2();
D::BBB();
}
Conclusion
Namespaces are for namespaces.
Classes are for classes.
C++ was designed so each concept is different, and is used differently, in different cases, as a solution to different problems.
Don't use classes when you need namespaces.
And in your case, you need namespaces.
There are a lot of people who would disagree with me, but this is how I see it:
A class is essentially a definition of a certain kind of object. Static methods should define operations that are intimately tied to that object definition.
If you are just going to have a group of related functions not associated with an underlying object or definition of a kind of object, then I would say go with a namespace only. Just for me, conceptually, this is a lot more sensible.
For instance, in your case, ask yourself, "What is a MyMath?" If MyMath does not define a kind of object, then I would say: don't make it a class.
But like I said, I know there are plenty of folks who would (even vehemently) disagree with me on this (in particular, Java and C# developers).
If you need static data, use static methods.
If they're template functions and you'd like to be able to specify a set of template parameters for all functions together then use static methods in a template class.
Otherwise, use namespaced functions.
In response to the comments: yes, static methods and static data tend to be over-used. That's why I offered only two, related scenarios where I think they can be helpful. In the OP's specific example (a set of math routines), if he wanted the ability to specify parameters - say, a core data type and output precision - that would be applied to all routines, he might do something like:
template<typename T, int decimalPlaces>
class MyMath
{
// routines operate on datatype T, preserving at least decimalPlaces precision
};
// math routines for manufacturing calculations
typedef MyMath<double, 4> CAMMath;
// math routines for on-screen displays
typedef MyMath<float, 2> PreviewMath;
If you don't need that, then by all means use a namespace.
You should use a namespace, because a namespace has the many advantages over a class:
You don't have to define everything in the same header
You don't need to expose all your implementation in the header
You can't using a class member; you can using a namespace member
You can't using class, though using namespace is not all that often a good idea
Using a class implies that there is some object to be created when there really is none
Static members are, in my opinion, very very overused. They aren't a real necessity in most cases. Static members functions are probably better off as file-scope functions, and static data members are just global objects with a better, undeserved reputation.
I want to summarize and add to other answers. Also, my perspective is in the world of header-only.
Namespaces
Pros:
simple solution for naming hierarchies
they carry no semantics, so it is simpler to read
can live in different files (headers)
can be extended
ADL
shortcut can be defined (using).
Plays well with operator overload
Can be used for branding (you can design your code and put a namespace over it without much though)
Cons:
everything is public
private things need unnamed namespace so it is not explicit
ADL (yes, some people despise ADL)
can be extended (this can be a bad thing, specially in combination with ADL, semantics of existing code can change by extending the namespace)
functions need to be defined (or declared) in order of use
Classes with static methods
Pros:
can have private components (function, variables) and they are explicitly marked.
classes can be friended
can be type-parametrized (templates)
can be template parameters themselves
can be instantiated
can be passed to functions (static functions behave like non-static method by default).
it is easier to find patterns and go from groups of independent functions and convert them to a proper class (eventually with non static members)
dependencies among classes is well defined
functions (the static method) can be defined in any order
Cons:
No ADL
cannot be extended
needs the keyword static everywhere (opportunity to make fun of the language)
an overkill to solve the naming problem alone. Difficult to read in that case.
the functions (static methods) always need qualification (myclassspace::fun). There is no way to declare shortcuts (using).
almost useless for operator overload, needs complicated friend mechanism for that.
can not be used for branding.
you need to remember end it with ; :)
In summary, classes with static methods are better units of code and allow more meta programming, and except for ADL and some syntactic quirks, can replicate all the features of namespaces, but they can be an overkill sometimes.
Companies, such as Bloomberg, prefer classes over namespaces.
If you don’t like ADL or operator overload, classes with static methods is the way to go.
IMO, it would be nice if namespace and classes are integrated to become two sides of the same coin.
For example identify a namespace in the language as a class were the methods are static by default.
And then be able to use them as template parameters.
I wouldn't be sure what to do with ADL (may be it could be restricted to symbolic operators functions alone, e.g. operatorX, which was the original motivation for operator overload and ADL in the first place)
I would prefer namespaces, that way you can have private data in an anonymous namespace in the implementation file (so it doesn't have to show up in the header at all as opposed to private members). Another benefit is that by using your namespace the clients of the methods can opt out of specifying MyMath::
Why would I choose one over the other as a means of organizing my software?
If you use namespaces, you will frequently hit a language defect that functions which call each other must be listed in a specific order, because C++ can't see definitions further down in the file.
If you use classes, this defect does not occur.
It can be easier and cleaner to wrap implementation functions in a class than to maintain declarations for them all or put them in an unnatural order to make it compile.
One more reason to use class - Option to make use of access specifiers. You can then possibly break your public static method into smaller private methods. Public method can call multiple private methods.
Both namespace and class method have their uses. Namespace have the ability to be spread across files however that is a weakness if you need to enforce all related code to go in one file. As mentioned above class also allows you to create private static members in the class. You can have it in the anonymous namespace of the implementation file however it is still a bigger scope than having them inside the class.