Sign in to follow this  

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

This topic is 4094 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
#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

This topic is 4094 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this