Join Regular Classroom : Visit ClassroomTech

Programming in C++ – codewindow.in

C++ Programing

// Namespace declaration
namespace my_namespace {
    int x; // variable
    void func(); // function
    class MyClass { /* class definition */ }; // class
}

// Accessing elements in the namespace
int main() {
    my_namespace::x = 42; // Accessing the variable x from the namespace
    my_namespace::func(); // Calling the function func() from the namespace
    my_namespace::MyClass obj; // Creating an object of the class MyClass from the namespace
    // ...
    return 0;
}

By using namespaces, you can create more modular and organized code, making it easier to manage and maintain larger projects.

namespace math_operations {
    int add(int a, int b) {
        return a + b;
    }
}

namespace string_operations {
    std::string concat(const std::string& str1, const std::string& str2) {
        return str1 + str2;
    }
}

int main() {
    int result = math_operations::add(5, 3); // Using the add function from the math_operations namespace
    std::string combined = string_operations::concat("Hello", " World!"); // Using the concat function from the string_operations namespace
    return 0;
}

By using namespaces, you can create cleaner and more organized code, minimize naming conflicts, and make it easier to collaborate with other developers.

// Part 1 of the program
#include 

void calculate() {
    std::cout << "Calculating in Part 1" << std::endl;
}

// Part 2 of the program
#include 

void calculate() {
    std::cout << "Calculating in Part 2" << std::endl;
}

int main() {
    calculate(); // Which "calculate" function should be called?
    return 0;
}

However, using namespaces, you can avoid the conflict:

// Part 1 of the program
#include 

namespace part1 {
    void calculate() {
        std::cout << "Calculating in Part 1" << std::endl;
    }
}

// Part 2 of the program
#include 

namespace part2 {
    void calculate() {
        std::cout << "Calculating in Part 2" << std::endl;
    }
}

int main() {
    part1::calculate(); // Calls the "calculate" function from Part 1
    part2::calculate(); // Calls the "calculate" function from Part 2
    return 0;
}

By using namespaces, you can clearly specify which “calculate” function you want to use, resolving any ambiguity and avoiding name collisions between identifiers in different parts of your program.

      

Go through our study material. Your Job is awaiting.

Recent Posts
Categories