0

Hello All,

I know that there is a similar thread about my problem, but I can't find it anymore.
Well basically I want 2 objects to know from each other. I know that in C++ I have to
use pointers to do that. I wrote some sample code to show you the problem:

#ifndef A_HPP_
#define A_HPP_
#include "B.hpp"

class A
{
public:
	//B* bpt;
	A();
	virtual ~A();
private:
	B* bpt;
};
#endif /*A_HPP_*/
=========================================
#include "A.hpp"
#include "B.hpp"
A::A()
{
}

A::~A()
{
}
========================================
#ifndef B_HPP_
#define B_HPP_
#include "A.hpp"

class B
{
public:
	//A* apt;
	B();
	virtual ~B();
private:
	A* apt;
};
#endif /*B_HPP_*/
=======================================
#include "B.hpp"
#include "A.hpp"
B::B()
{
}

B::~B()
{
}

======================================
The error I get is:

**** Build of configuration Linux GCC for project TestCrossPt ****

make all
g++ -c A.cpp
B.hpp:13: error: ISO C++ forbids declaration of ‘A’ with no type
B.hpp:13: error: expected ‘;’ before ‘*’ token
make: *** [A.o] Error 1
======================================
And this is the makefile I use:

all: test

test: A.o B.o TestCrossPt.o
g++ A.o B.o TestCrossPt.o -o test.exe -lpthread

A.o: A.cpp
g++ -c A.cpp

B.o: B.hpp
g++ -c B.cpp

TestCrossPt.o: TestCrossPt.cpp
g++ -c TestCrossPt.cpp
==========================================
Well, I am pretty new to C++ so please use easy language :)

many thanks

Rick

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by Rick1980
0

The problem is that you are recursively including A.hpp and B.hpp. So solve the problem, just pre-declare the classes

#ifndef B_HPP_
#define B_HPP_
class A; 
#include "A.hpp" 
class B
{
public:	
      B();	
      virtual ~B();
 private:	
      A* apt;
};
#endif /*B_HPP_*/
0

Brilliant, thank you very much for the quick and helpful answer :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.