954,487 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

2 Classes, each includes the other, compile errors

Hey All,

I've been stumbling into the same (annoying little) problem a couple of times, and I'd like to find out how to fix it properly.

Pseudo code

// file A.hpp
#include "classB.hpp"
class A { A() };


// file A.cpp
A::A() { }
// file B.hpp
#include "classA.hpp"
class B { B() };


// file B.cpp
B::B() { }


Notice how they're basically two normal classes, except that the both include the other.
I do have #ifndef CLASS_A / CLASS_B in the headers (header gaurds).

If i do #include "classA.hpp" in file classB.cpp I get errors like so:
error: ‘A’ was not declared in this scope

If I do a dummy class class B; then I can't use any of the functions in that class, because it complains that the class doesn't have that functionality.

Help apprecicatied, as I'm not sure how to design for such a situation... :)
-Harry

harryhaaren
Light Poster
27 posts since May 2009
Reputation Points: 10
Solved Threads: 2
 

i hope this could be helpful

#include <iostream>
using namespace std;

class A;

class B{
	A *obj;
public :
	B(){obj=0;}
	~B(){if(obj)delete obj;}
	void helloFromA();
};
class A{
public :
	void hello()
	{
		cout<<"hello from A"<<endl;
	}
};


void B::helloFromA()
{
	if(!obj)
	{
		obj=new A();;
	}
	obj->hello();
}
mazzica1
Junior Poster
147 posts since Oct 2011
Reputation Points: 9
Solved Threads: 27
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: