C++ – circular dependencies

Since the down of time mankind seek the solution to the circular dependencies in C++. Well – may be ot exactly since the “down of time” and definitly not the whole of the mankind – but it have been “always” a problem.

Traditional solution was to forward-declarate it:

class A;

class B
{
public:
  B(A *) {}
};

class A
{
  static B b;

};

However it have its limitations. For example B cannot call A methods making such solutions useless. Other solution is spliting functions and class declaration – however it may cause problems if they will not match (for example some functions remain undefined):

class A;

class A
{
  static B b;
public:
  void doIt();
};

class B
{
public:
  B(A *);
  void doSomething();
};

void A::doIt()
{
  b.doSomething();
}

B::B(A *a)
{
  if(a != NULL)
    a->doit();
}

void B::doSomething()
{

}

There is solution, at least working on gcc 4.4. Let’s define B as a template:

template
class B
{
public:
  B(A *a)
  {
    if(a != NULL)
      a->doit();
  }
  void doSomething() {}
};

class A
{
  static B b;
public:
  void doit()
  {
    b.doSomething();
  }
};

Probably we consider writing each time <![CDATA[B]]> waste of space. We can simply forward-declare class and set the default arguments:

class A;

template
class B
{
public:
  B(A *a)
  {
    if(a != NULL)
      a->doit();
  }
  void doSomething() {}
};

class A
{
  static B b;
public:
  void doit()
  {
    b.doSomething();
  }
};
Advertisements
This entry was posted in Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s