Using a namespace in place of a static class in C++? - c++

Is it good or okay practice to use a namespace as a static class? For example:
namespace MyStaticFunctions {
void doSomething();
}
Versus:
class MyStaticFunctions {
static void doSomething();
}

There's no such thing as a "static class" in C++, so from a C++ point of view you're not using it "as a static class", you're using it "as a namespace". It's certainly accepted practice to use namespaces to group functions together.
It's up to you, though, how big you want the groups to be. It's not unusual for C++ libraries to use a single namespace for the whole public interface. That might come as a surprise to someone who is used to (say) Java, where classes are often used to group together smaller numbers of static methods. Since C++ was here first, you could say that Java is using classes as namespaces.
So, in C++ you don't tend to see classes similar to java.util.Collections or java.lang.Math, full of static members. If you want groups of functions like that in C++, use namespaces.
The exception (isn't there always a special case in C++?) is traits types like std::numeric_limits<T>, where the template parameter makes the class do something that a namespace can't do. You could define a namespace numeric_limits containing function templates max<T>(), min<T>() etc, but it's not as good. Firstly, it groups things slightly differently, the type T appears "lower down the hierarchy". Secondly it doesn't do everything that a traits type does, because there's no such thing as an "object template" that would let you define a value numeric_limits::digits<T>.
I don't know C# well enough to comment on the practical uses of static classes there, but AFAIK it's just a class restricted to having no non-static members, so it's analogous to those Java classes.

In C++, you are actually encouraged at the language level to use a namespace rather than a class containing only static methods because of Koenig's lookup (aka Argument Dependent Lookup).
Example:
namespace geometry {
struct Point { int x, y; };
double distance_from_center(Point const& p) {
return sqrt(p.x * p.x + p.y + p.y);
}
} // namespace geometry
int main() {
geometry::Point const p{3, 4}; // must qualify
std::cout << distance_from_center(p) << "\n"; // not qualified
}
If distance_from_center is written as a static method in a class, then you need to explicitly qualify it each time.

It's a tough and interesting question for me personally, so decided to share my humble opinion
Considering the difference between "static" class (only static members) and namespace:
a namespace can be scattered over multiple files: additional flexibility but should be used carefully.
a namespace provides argument dependent lookup (see Matthieu M. answer): useful in specific situations
a "static" class can have access modifiers and can form an hierarchy: I think private members declared in class interface and visible to its clients is a C++ feature that was dictated more by technical, not logical reasons. I don't see any benefits of private static members. Protected members for "static" hierarchy? Never seen any.
a "static" class can be a "template", in addition to template members: see Steve Jessop's answer for a great example from STL
From maintenance point of view, sometimes you decide to make a class "static" (like a singleton), but then requirement changed and you need multiple instances. "Static" class would be easier to transform than namespace.
And, finally, to answer your question:
if you don't need special features of "static" class or namespace, use what you like more :)

It depends.
Is the method logically related to a class? If so, make it a member, otherwise place it in a namespace.
Functionally, they're the same, but there's more to code than function, right? For example, consider a method that returns the name of the class:
struct MyClass
{
static std::string getName() { return "MyClass"; }
}
You could obviously place the method outside, in a namespace, and get the same result, but it logically belongs to the class.

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.

Difference between classes and namespaces?

I'm looking at namespaces and I don't really see a difference between these and classes.
I'm teaching myself C++ I've gotten several books online, so I know I'm not learning the most effectively. Anyway, can someone tell me the difference between the two, and what would be the best time to use a namepace over a class? Also, I don't see much about structs in the book I'm reading.
Is this the format?
struct go
{
goNow(){ cout << "go Now"};
}
Thanks in advance for your assistance.
Classes and structs define types. You can create an object of a type. Namespaces simply declare a scope inside which other types, functions, objects, or namespaces can exist. You can't create an object of type std (unless of course you created a type called std, which would hide the std namespace).
When you define a function inside a struct/class (a method) you're saying "This function is a fundamental operation on the associated data". When you define a function inside a namespace you're saying "This function is logically related to other functions, types, and objects in the namespace"
Edit
It's probably worth pointing out that "everything is an object" languages like Java and C# regularly use classes as if they were namespaces because they don't allow "free" functions. This may be where the confusion comes from. If you have a class in another language that contains nothing but static members, you would want to use a namespace and free functions in the C++ version.
You can search on the web for the differences and i am sure you will find many; but the following are important IMHO:-
You can reopen a namespace and add
stuff across translation units. You
cannot do this with classes.
Using a class implies that you can
create an instance of that class, not
true with namespaces.
You can use using-declarations with
namespaces, and that's not possible
with classes unless you derive
from them.
You can have unnamed namespaces.
A namespace defines a new scope and members of a namespace are said to have namespace scope. They provide a way to avoid name collisions (of variables, types, classes or functions) without the inconvenience of handling nested classes.
A class is a data type. If you have a class named Foo, you can create objects of class Foo and use them in many ways.
A namespace is simply an abstract way of grouping items together. Normally, you cannot have two functions in your program named bar(). If you place them in separate namespaces, then they can coexist (for example, as A::bar() and B::bar()). A namespace cannot be created as an object; think of it more as a naming convention.
If you are writing code that you want to be associated with an object that you can define and use as a variable, write a class. If you are writing an API or library and you want to wrap up all of the functions and constants so that their names don't clash with anything that the user might have written, use a namespace.
A namespace is a way of grouping identifiers so that they don't clash.
A class is defeinition of an object that can be instantiated (usually) and which encapsulates functionallity and state.
Namespaces and classes are entirely different, and serve different purposes. They have some syntactic similarity.
Structs are classes, with a different default access specifier (public for struct, private for class) - in all other aspects they are the same.
One major difference is that namespaces can be re-opened, but classes cannot be:
namespace A {
int f1();
}
namespace A {
int f2();
}
is legal, but:
class A {
int f1();
};
class A {
int f2();
};
is not
From wikipedia
In general, a namespace is an abstract container providing context for the items (names, or technical terms, or words) it holds and allowing disambiguation of homonym items having the same name (residing in different namespaces).
As a rule, names in a namespace cannot have more than one spelling, that is, its components cannot share the same name. A namespace is also called a context, as the valid meaning of a name can change depending on what namespace applies. Names in it can represent objects as well as concepts, whether it is a natural or ethnic language, a constructed language, the technical terminology of a profession, a dialect, a sociolect, or an artificial language (e.g., a programming language).
On the other hand A class defines a type.
A namespace may contain multiple classes.
EDIT
One difference would be this:
You can have unnamed namespaces but you can't have a unnamed class
namespace{ //fine
//some code....
}
class{ //illegal
}

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.