Darshan Kalola
Darshan Kalola

Reputation: 67

How do I properly use "using namespace foo?"

I am slightly confused by the using namespace x in c++. Why would it be incorrect in this context? Does "using namespace" only applicable to the other files we are #including?

#include <iostream>
using namespace A;


namespace A {
    void print() {

std::cout << "From namespace A" << std::endl;
    }
}

namespace B {
    void printB() {
        std::cout << "From namespace B" << std::endl;
    }
}


int main() {
    print();
    printB(); 
}

Upvotes: 1

Views: 78

Answers (2)

user0042
user0042

Reputation: 8018

As the error messages tell you here these functions aren't declared within your current scope.
everything you call with an unspecified namespace is considered to be found in the global namespace as ::print, ::printB.

You need to use the namespace scope operator (::) like follows:

A::print();
B::printB(); 

or a using statement:

using A::print;
using B::printB;

Upvotes: 2

Martin Beckett
Martin Beckett

Reputation: 96109

Using namespaces would allow you to have both the functions called print. You would use them as A::print() and B::print() rather than having to rename one of them printB()

Upvotes: 1

Related Questions