A namespace and a class are both used to organize C++ programs, but they serve different purposes. A namespace groups related identifiers to avoid naming conflicts, whereas a class defines a user-defined type for creating objects.
- Namespaces help organize code and prevent name collisions.
- Classes encapsulate data and behavior into reusable objects.
Namespace
A namespace is a named scope that groups related identifiers such as variables, functions, and classes. It helps avoid conflicts when multiple libraries or modules contain identifiers with the same name.
- Groups related identifiers under a common name.
- Prevents naming conflicts between different libraries.
- Cannot be instantiated as an object.
- Can be reopened and extended across multiple declarations.
#include <iostream>
using namespace std;
namespace Math {
int square(int x) {
return x * x;
}
}
int main() {
cout << Math::square(5);
return 0;
}
Output
25
Explanation: The function square() belongs to the Math namespace and is accessed using the scope resolution operator (Math::).
Class
A class is a user-defined data type that encapsulates data members and member functions into a single unit. Objects are created from a class to represent entities with data and behavior.
- Used to create objects.
- Supports encapsulation through access specifiers.
- Can contain data members and member functions.
- Supports object-oriented features such as inheritance and polymorphism.
#include <iostream>
using namespace std;
class Student {
public:
void display() {
cout << "Student Object";
}
};
int main() {
Student s;
s.display();
return 0;
}
Output
Student Object
Explanation: The class Student defines a user-defined type, and an object s is created to access its member function.
Difference Between Namespace and Class
| Feature | Namespace | Class |
|---|---|---|
| Purpose | Organizes identifiers and avoids naming conflicts | Defines a user-defined data type |
| Object Creation | Cannot create objects | Objects can be created |
| Data Members | Cannot store object data | Can contain data members |
| Member Functions | Can contain functions | Can contain member functions |
| Access Control | Does not support access specifiers | Supports public, private, and protected |
| Inheritance | Not supported | Supported |
| Reopening | Can be reopened and extended | Cannot be redefined after declaration |
| Alias Support | Supports namespace aliases | Supports type aliases using using or typedef |