Difference between namespace and class

Last Updated : 11 Jul, 2026

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.
C++
#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.
C++
#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

FeatureNamespaceClass
PurposeOrganizes identifiers and avoids naming conflictsDefines a user-defined data type
Object CreationCannot create objectsObjects can be created
Data MembersCannot store object dataCan contain data members
Member FunctionsCan contain functionsCan contain member functions
Access ControlDoes not support access specifiersSupports public, private, and protected
InheritanceNot supportedSupported
ReopeningCan be reopened and extendedCannot be redefined after declaration
Alias SupportSupports namespace aliasesSupports type aliases using using or typedef
Comment