Main BLOGGER
Google
WWW THIS BLOG
Thursday, July 07, 2005
 
C++ class circular reference

Here is the thorough example:

  1. class A refers to class C
  2. class C refers to class A

The tricks are the forward reference and the avoidance of double including.

Then, we are free to go.

------------------------A.cpp---------------------

#include "C.h" //important, it is required to get definition of class C

#include "A.h"

void A::SomeMethod()

{

m_pC = new C();

m_pC-SomeMethod();

}

------------------------End A.cpp---------------------

--------------------------- A.h ------------------

#ifndef A_H //to avoid double including

#define A_H

/* Class A definition */

class C; //forward reference

class A

{

public:

A(){};

~A(){};

void SomeMethod();

private:

C* m_pC;

};

#endif

---------------------------End A.h-------------------------

--------------------------- C.h ------------------

#ifndef C_H //to avoid double including

#define C_H

/* Class C definition */

#include "A.h"

class C

{

public:

C(){};

~C(){};

void SomeMethod(){};

private:

A* m_pA;

};

#endif

---------------------------End C.h-------------------------

----------------------------main.cpp----------------------

#include "C.h"

#include

int main()

{

C c;

c.SomeMethod();

}

---------------------------End main.cpp-----------------

Compile: g++ -c A.cpp; g++ -c main.cpp; g++ -o m main.o A.o




<< Home

Powered by Blogger

Google
WWW THIS BLOG