Namespaces vs classes

Started by
1 comment, last by DarkNebula 20 years, 5 months ago
I'm still new to c++ and was wondering what is the difference between namespaces and classes? Namespaces seem easier to use but is there a drawback of some sort or some "features" I couldn't use? Thanks for any reply :D Or am I not understanding something about them... - DarkNebula [edited by - DarkNebula on November 12, 2003 8:00:07 PM]
Advertisement
I''m not an expert on the subject, but I''ll tell you a few things, and the more experienced here can fill in the rest.

One important distinction is that namespaces are ''open'' while classes are ''closed''. That is, you can only declare a class, such as

class MyClass
{
// Lots of stuff
};

once.

However, you can add things to a namespace anywhere in your program. Let''s say you''re using the namespace MyEngine to wrap all of your classes. In every header file for every class you would say:

namespace MyEngine
{
class ThisParticularClass
{
// Lots of stuff
};
}

Classes are a fundamental building block of object oriented programming. You instantiate objects from them, and they have many powerful features such as private data and functions, polymorphism, inheritance, etc.

Namespaces (AFAIK) are always public and don''t have many of the features that classes do. They are often used to ''wrap'' a set of functions or classes to prevent name clashing. For example, say you have a Vector3 class. Well, everyone else probably has a Vector3 class too, so if you try to merge your library with someone else''s, you run into problems. But if you wrap all of your classes in a namespace, your Vector3 class becomes MyEngine::Vector3, which distinguishes it from YourEngine::Vector3.

Ok, that really only scratches the surface. I''ll let someone else pick it up from here...

You can only have one "instance" of a namespace(instance is in quotes, because it''s not really an instance of anything), and many instances of the same class. Namespaces are used for grouping functions and classes, mostly for avoiding name conflicts. Classes, or objects, as the instances are called, can contain data, different data for each object and are used for for almost everything in an object oriented program.

I won''t explain more, because it''s obvious once you learn what classes and objects are properly. Also, I''m pretty sure there was a thread about the same thing not so long ago.

This topic is closed to new replies.

Advertisement