Suppose you have a class declare in a namespace, like this:
#pragma once
namespace Test
{
class foo
{
public:
foo(void);
~foo(void);
};
};
#include "foo.h"
namespace Test
{
foo::foo(void)
{
}
foo::~foo(void)
{
}
};
And you want to use that foo class in a another class, with a forward declaration:
#pragma once
class foo;
class bar
{
foo * m_foo;
public:
bar(void);
~bar(void);
};
#include "bar.h"
#include "foo.h"
using namespace Test;
bar::bar(void)
{
m_foo = new foo;
}
bar::~bar(void)
{
}
Most likely you’ll get some errors, like this (issues by VS2008 compiler)
error C2872: ‘foo’ : ambiguous symbol
error C2512: ‘foo’ : no appropriate default constructor available
The problem is that for the compiler it is ambiguous whether that foo and Test::foo are the same or not. To remove the ambiguity you should specify that the forward declared foo type is the same with the one from the namespace Test. The best way to do that is like this:
namespace Test
{
class foo;
};
class bar
{
Test::foo * m_foo;
public:
bar(void);
~bar(void);
};
The only thing that I should mention is that approach is not allowed for the types from namespace std, as Herb Sutter explains here.
Thanks for the post! I had this ambiguity problem with forward declaration in MS Visual Studio C++, and it helped me resolve it.
Thank you so much! This post was extremely clear and helpful.