Ghansham
Ghansham

Reputation: 498

Accessing one namespace data member into another

How do I access the y (which is inside namespace n2), from n1 namespace: The test code is below:

#include<iostream>
using namespace std;

namespace n1
{
    int x =  20;
    int m = ::n2::y;
    void printx()
    {
        cout << "n1::x is " << x << endl;
        cout << "n2::y is " << m << endl;
    }
}

namespace n2
{
    int y = 10;
}

int main()
{
    cout << n1::x << endl;
    n1::printx();
    cout << n2::y << endl;

    return 0;
}

I am getting below error: test.cpp:7:15: error: ‘::n2’ has not been declared int m = ::n2::y;

Upvotes: 0

Views: 38

Answers (1)

Akhil Thayyil
Akhil Thayyil

Reputation: 9403

Just change the order, so that n2 is resolvable inside n1 :

#include<iostream>
using namespace std;


namespace n2
{
    int y = 10;
}

namespace n1
{
    int x =  20;
    int m = n2::y;
    void printx()
    {
        cout << "n1::x is " << x << endl;
        cout << "n2::y is " << m << endl;
    }
}


int main()
{
    cout << n1::x << endl;
    n1::printx();
    cout << n2::y << endl;

    return 0;
}

Upvotes: 2

Related Questions