1

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(); 
}
2

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.