Jump to content
  • Advertisement
Sign in to follow this  
kloffy

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

This topic is 4383 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
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!