Namespaces in C++ provide a mechanism to group related code elements (functions, classes, variables) under a named scope, helping to avoid naming conflicts and organize code logically.
#include <iostream>
namespace Mathematics {
const double PI = 3.14159;
double calculateCircleArea(double radius) {
return PI * radius * radius;
}
}
int main() {
double radius = 5.0;
std::cout << "Area of circle with radius " << radius << " is: "
<< Mathematics::calculateCircleArea(radius) << std::endl;
return 0;
}
Mathematics
::
#include <iostream>
namespace Physics {
const double G = 9.81; // Acceleration due to gravity
double calculateFallingDistance(double time) {
return 0.5 * G * time * time;
}
}
using namespace Physics;
using std::cout;
using std::endl;
int main() {
double time = 3.0; // seconds
cout << "Distance fallen in " << time << " seconds: "
<< calculateFallingDistance(time) << " meters" << endl;
return 0;
}
using namespace
directive to bring all names from Physics
into current scopeusing
declarations for specific names from the std
namespace#include <iostream>
namespace Science {
namespace Chemistry {
double calculateMolarity(double moles, double liters) {
return moles / liters;
}
}
}
namespace {
// This function is only accessible within this translation unit
void printResult(double molarity) {
std::cout << "The molarity is " << molarity << " mol/L" << std::endl;
}
}
int main() {
double moles = 0.5;
double liters = 2.0;
double molarity = Science::Chemistry::calculateMolarity(moles, liters);
printResult(molarity);
return 0;
}
Science::Chemistry
std
namespace contains all standard library componentsNamespaces in C++ provide a powerful mechanism for organizing code and preventing naming conflicts. They allow developers to group related functionality, create hierarchical code structures, and manage the scope of identifiers. Through the use of namespace directives, declarations, and the scope resolution operator, C++ programmers can control how names from different namespaces are used in their code. Proper use of namespaces is crucial in large-scale software development and when working with multiple libraries.
Previous Page | Course Schedule | Course Content