-4

Namespaces and classes are two different concepts in C++. Namespace is there only to prevent name collision, instead a class is a user-defined type.

Than why they use the same :: syntax?

For example:

namespace::function();
class::function();
Christian Hackl
  • 26,144
  • 3
  • 29
  • 57
iianfumenchu
  • 848
  • 8
  • 14

2 Answers2

6

Both namespaces and classes form scopes. Scope is a concept that works rather uniformly with both namespaces and classes: there's class scope and there's namespace scope in C++ (as well as other kinds of scopes). And since :: is a scope resolution operator, there's nothing unusual in it being used with namespaces and classes in syntactically similar fashion.

AnT
  • 302,239
  • 39
  • 506
  • 752
2

Because classes, just like namespaces introduce a (usually named) scope. The scope resolution operator works the same with classes and namespaces. There would be no advantage in adding more operators for doing the same thing.

If classes didn't introduce a scope, there would be trouble:

struct buffer {
    int size, *data;
};

struct list {
     node* head;
     int size; // oops, name conflict!
};

Clearly, classes must introduce a scope for their members.

eerorika
  • 223,800
  • 12
  • 181
  • 301