cnd
cnd

Reputation: 33784

How to create to classes which is using each other in different files?

For example I have a class A defenition

class A {
 ... 
 }

in a.h

and B in b.h

class B {
 ... 
 }

in a.h I need #include "b.h" and in b.h I need #include "a.h" but it's recursive fault for compiler.

I can trick it in one file with pre defention like that

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

but for clarity... I want to separate them from each other, how can I make it?

Upvotes: 1

Views: 90

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258678

Forward declarations is the way to go:

//B.h
class A;
class B
{
};

and

//A.h
class B;
class A
{
};

Note that this won't work if you need a full type, i.e. a data member of type A or B is needed by the respective other class (method parameters, return types, pointers or references would work with an incomplete type).

Upvotes: 2

Related Questions