breaking circular dependency?!

O

Oliver Kowalke

Hi,
how could following problem be solved (not the same base class)?

// A.h

class A
{
private:
   const X move_()
   { ... }

public:
   const B f()
   { return B( move_() ); }
};


// B.h

class B
{
private:
   const X move_()
   { ... }

public:
   const A f()
   { return A( move_() ); }
};
 
R

Rolf Magnus

Oliver said:
Hi,
how could following problem be solved (not the same base class)?

What base class?
// A.h

class A
{
private:
const X move_()
{ ... }

public:
const B f()
{ return B( move_() ); }
};


// B.h

class B
{
private:
const X move_()
{ ... }

public:
const A f()
{ return A( move_() ); }
};

Don't implement the functions in the header, but in the implementation file.
Then put a forward declaration before the class definition.
 
O

Oliver Kowalke

Rolf said:
What base class?

I mean I don't want to have a (shared) base class (as a suggestion)
Don't implement the functions in the header, but in the implementation
file. Then put a forward declaration before the class definition.

forward declarations work for references or pointer in the header - doesn't
the compiler need to know the size of A / B in the header because it A and
B are returned by value and not as refernce or pointer?
 
R

Rolf Magnus

Oliver said:
forward declarations work for references or pointer in the header -
doesn't the compiler need to know the size of A / B in the header because
it A and B are returned by value and not as refernce or pointer?

No.
 
V

Vaclav Haisman

Oliver Kowalke wrote, On 28.12.2008 18:38:
Hi,
how could following problem be solved (not the same base class)?

// A.h

class A
{
private:
const X move_()
{ ... }

public:
const B f()
{ return B( move_() ); }
};


// B.h

class B
{
private:
const X move_()
{ ... }

public:
const A f()
{ return A( move_() ); }
};
Using forward declaration and moving the methods implementation to place
where the forward declared class is complete. Something like this:


// X.h
struct X
{ };


// A.h
class B;

class A
{
private:
const X move_()
{ return X (); }

public:
A (X = X ())
{ }

const B f();
};


// B.h
class A;

class B
{
private:
const X move_()
{ return X (); }

public:
B (X = X ())
{ }

const A f();
};


// A.cpp
#include "A.h"
#include "B.h"

const B A::f()
{ return B( move_() ); }


// B.cpp
#include "A.h"
#include "B.h"

const A B::f()
{ return A( move_() ); }


// main.cpp
int main ()
{
A a;
B b;

A aa = b.f();
B bb = a.f();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top