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.
Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. In programming, a library is a collection of precompiled routines that a program can use.
This allows organizing the elements of programs into different logical scopes referred to by names. Namespaces provide the space where we can define or declare identifiers i.e. names of variables, methods, classes, etc. Namespace is a feature added in C++ and is not present in C.
Two classes with the same name can be created inside 2 different namespaces in a single program. Inside a namespace, no two classes can have the same name.
Namespaces are used in C# to organize and provide a level of separation of codes. They can be considered as a container which consists of other namespaces, classes, etc. A namespace can have following types as its members: Namespaces (Nested Namespace)
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:-
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With