andrewtc
andrewtc

Reputation: 741

How do I convert my program to use C++ namespaces?

My code was working fine, until I tried to wrap all of my class definitions in a namespace.

// "Player.h"
#include "PhysicsObject.h"
namespace MaelstromII
{
    class Player : public MaelstromII::PhysicsObject
    {
        // ...
    };
}

// "PhysicsObject.h"
#include "GameObject.h"
namespace MaelstromII
{
    class PhysicsObject : public MaelstromII::GameObject
    {
        // ...
    };
}

// "GameObject.h"
namespace MaelstromII
{
    class GameObject
    {
        // ...
    };
}

When I compile in Visual Studio, I get a bunch of these errors:

error C2039: 'PhysicsObject' : is not a member of 'MaelstromII'

It complains about GameObject, too.

Does anyone know why this is?

Upvotes: 1

Views: 203

Answers (2)

andrewtc
andrewtc

Reputation: 741

Turns out the trouble was caused by a circular dependency in my code somewhere else. After fixing that problem, my code compiled fine.

Evidently, there is no difference between this:

namespace Foo {
    class Bar {}
    class Bar2 : public Bar {}
}

And this:

namespace Foo {
    class Bar {}
    class Bar2 : public Foo::Bar {}
}

The compiler resolves them the same way.

Upvotes: 0

Narfanator
Narfanator

Reputation: 5813

I'm not 100%, but I think what's going on when you say

namespace Foo
{
    class Bar : public Foo::BarBase {}
}

is the same as:

class Foo::Bar : public Foo::Foo::BarBase {}

When you're in a namespace, you don't need to use the namespace:: specifier to access other things in that namespace.

Upvotes: 2

Related Questions