1

I am unable to run the following code. As namesapces are different, why there are still showing errors as mentioned below? error: conflicting declaration 'NS2::Base B' NS2::Base B;

#include<iostream>
using namespace std;

namespace NS1
{
    class Base
    {
        int x=4;
        public:
            void disp()
            {
                cout<<x<<endl;
            }
    };
}

namespace NS2
{
    class Base
    {
        int x=7;
        public:
            void disp()
            {
                cout<<x<<endl;
            }
    };
}

int main()
{
    NS1::Base B;
    NS1:B.disp();
    NS2::Base B;
    NS2::B.disp();
}
Bahubali
  • 141
  • 1
  • 2
  • 8

2 Answers2

3

Namespaces contain only what is declared inside them, in your case the two classes Base. The two objects called B however are not declared in any namespace (but are both scoped to the function main), so you get a conflicting declaration error. It doesn't matter that the associated classes where declared in different namespaces.

Knoep
  • 858
  • 6
  • 13
  • the `B` declarations are not declared in the global namespace, or global scope (that'd be if they were defined above main), they are scoped to the function – kmdreko Oct 19 '17 at 01:29
  • @vu1p3n0x You're right, I should've been more careful. Give me a minute to figure out how to express this properly. – Knoep Oct 19 '17 at 01:31
  • @vu1p3n0x What about that? I'm really not sure, what the correct terminology is. – Knoep Oct 19 '17 at 01:35
  • thats fine. When talking about declarations, everything has a *scope* whether it be global, function, class, and a few others. for info: [Scope](http://en.cppreference.com/w/cpp/language/scope) – kmdreko Oct 19 '17 at 01:42
  • @vu1p3n0x Scope wasn't the problem, but which namespace they're actually in (as this is what the question was all about). But accoding to [this question](https://stackoverflow.com/questions/10269012/global-scope-vs-global-namespace) it seems to be correct to say that they are not in any namespace at all. – Knoep Oct 19 '17 at 09:47
1

Just the class Base is part of namespace NS1, B1 is just an object of type NS1::Base defined in main() not in NS1. Same goes for B2 and NS2. Thats why you can't call function using scope resolution operator on B1. Objects are defined in main() so you have too keep names different too

int main()
{
    NS1::Base B1;
    B1.disp();
    NS2::Base B2;
    B2.disp();
}
Eurus_
  • 41
  • 4