Raphael
Raphael

Reputation: 127

invalid forward declaration of struct

--EDIT -- So sorry that I confused people, I just quickly typed this code out instead of copy and pasting, so I actually do #ifndef A_H #define A_H in my code. Ive changed the below code to show that
-- End edit --

I have two classes which each contain a pointer to an instance of the other class, but this is creating problems for me . My code is similar to the following

// A.h
#ifndef A_H
#define A_H

class B; // compiler error here

class A
{
  B* foo;
  // other members and functions
};

#endif

// A.cpp
#include "A.h"
#include "B.h"
/*
 declare functions and use methods in both A and B
*/

// B.h
#ifndef B_H
#define B_H

class A;

class B
{
  A** bar;
// other stuff
};

#endif

//B.cpp
#include "A.h"
#include "B.h" 
/*
declare functions and use methods in both A and B
*/

I was told that forward declaring the other class int he header file then including the other file in the cpp file would work, but on the marked line I get an error that just says "forward declaration of 'struct b'"

Can anyone tell me what I'm doing wrong?

Upvotes: 1

Views: 1144

Answers (1)

PiotrNycz
PiotrNycz

Reputation: 24450

Include one header, let say b.h in a.h. Do not forward declare B in a.h. b.h can stay as it is.

Otherwise you get sth like

class B {};
....
class B;

It is always wise to do preprocessing only on such errors.

Upvotes: 3

Related Questions