Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All
I am facing a problem.
let suppose i have two classes.class A and class B.
in class A i defines the object of class B,and in class B i defines the object for class A.
When i try to run the code it show the error that to place a semicolon before the classA .
the code is something like this .

#include"B_wnd.h"
class A_wnd{
int xy;
B_wnd b_obj;
};







in class B declaration i am using like this



#include"A_wnd.h"
class B_wnd{
int bx;
A_wnd a_obj;
};




when i try to ru the code ,i get the error.
can any one help me in getting rid off from this problem.
Posted

That's a circular reference, and you can't do that. Refactor your code.
 
Share this answer
 
Comments
vaibhavbvp 25-Dec-11 10:52am    
Hi Sir
can you help me to refactor this code,beacuse i ahve no idea how to overcome this
C++
#include"B_wnd.h"
class A_wnd{
int xy;
B_wnd b_obj;
};

#include"A_wnd.h"
class B_wnd{
int bx;
A_wnd a_obj;
};


First of all why do you need a circular reference? Any real need or you want just to test?

First of all the headers will have circular reference. You can use a include guard to over come that. Mostly all advanced C/C++ processors can avoid it, but always when you include headers use include guards. In Microsoft VCC then I think you can use
C++
#pragma once


After you overcome this you have a second problem.

Suppose you create an object of type A_wnd.
When the constructor of A_wndis called it calls the constructors of B_wnd. Inside this again constructor of A_wnd will be called. This is a recursive problem. You will go out of stack and there will be crash.

You can use pointers or reference instead of real objects.
 
Share this answer
 
Use this:
C++
//A_wnd.h
#ifndef A_H
#define A_H
#include "B_wnd.h"

class B_wnd;

class A_wnd
{
    public:
	B_wnd* m_b;
};

#endif


C++
//B_wnd.h
#ifndef B_H
#define B_H

#include "A_wnd.h"
class A_wnd;

class B_wnd
{
	public:
	A_wnd* f;
};
#endif



2 important issues:
1. ifndef - to avoid redefinition
2. Forward definition (class B_wnd; for example).
 
Share this answer
 
v2
Comments
BrainlessLabs.com 25-Dec-11 12:41pm    
Nice, but you need not use the #include "A_wnd.h" and #include "B_wnd.h" if you want to use pointers. This will reduce some work for the pre processor engine.
arielb 26-Dec-11 13:56pm    
thanks, but if u will not include not A nor B, how will the classes know each other exist?
i tried removing the includes - didnt work.
Espen Harlinn 31-Dec-11 8:26am    
5'ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900