• Advertisement
Sign in to follow this  

[C++] Cyclic dependency between classes in different namespaces

This topic is 4169 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I know cyclic dependencies are bad design and all that, but is it possible to do something like this?
#include <iostream>

namespace Bob
{
  class A;
}

namespace Alice
{
  class A {
	public:
	int type;
	A(int _type): type(_type){}
	operator Bob::A() { 
	  return Bob::A(type);
	}
  };
}

namespace Bob
{
  class A {
	public:
	int type;
	A(int _type): type(_type){}
	operator Alice::A() { 
	  return Alice::A(type);
	}
  };
}

int main(int argc, char* argv[])
{
	Bob::A b(1);
	Alice::A a = b;

	std::cout << a.type << ',' << b.type << '\n';

	return 0;
}

(The above example doesn't work. Compilation results in a "undefinded type" error at "operator Bob::A()")

Share this post


Link to post
Share on other sites
Advertisement
#include <iostream>

namespace Bob
{
class A;
}

namespace Alice
{
class A {
public:
int type;
A(int _type): type(_type){}
// declaration without inline definition
operator Bob::A();
};
}

namespace Bob
{
class A {
public:
int type;
A(int _type): type(_type){}
operator Alice::A() {
return Alice::A(type);
}
};
}

namespace Alice
{
// definition after class Bob::A is fully defined
A::operator Bob::A() {
return Bob::A(type);
}
}

int main(int, char**)
{
Bob::A b(1);
Alice::A a = b;

std::cout << a.type << ',' << b.type << '\n';
}

Σnigma

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement