Is it legal to forward declare in another header’s file? For example:
#ifndef _MAIN_H_
#define _MAIN_H_
class ClassA;
class ClassB;
#include "classa.h"
#include "classb.h"
#endif
#ifndef _CLASSA_H_
#define _CLASSA_H_
#include "main.h"
class ClassA
{
public:
ClassB b;
};
#endif
#ifndef _CLASSB_H_
#define _CLASSB_H_
#include "main.h"
class ClassB
{
public:
ClassA a;
};
#endif
Both class A and class B depend on each other, and both have an object of the other type. What I did was forward declared both classes in another file. Is there a clean way to do this?
In general it is legal to forward-declare classes across headers.
However, in your example, you are instantiating both classes in each other, which is absolutely illegal!
To show the reasoning behind this, think about the following:
Let
ClassAtake 1 byte withoutbandClassBalso 1 byte withouta.Now, include
b:ClassAnow takes 2 byte. Now includea:ClassBnow takes 3 bytes. Now we have to update the size ofClassAto 4 bytes due to the size increase ofClassB. Following that logicClassBis now 5 bytes,ClassA6 bytes,ClassB7 bytes…….To deal with this, you probably would like to change the type of (at least) one of
aandbto a pointer or reference to the respective class. When doing this (in c/c++), make sure you understand your memory management!The solution to your original problem could then look as follows:
ClassA.h
ClassB.h
Note that ClassB.h requires ClassA.h since for demonstration purposes:
ClassBcontains a full object of typeClassA, so the definition ofClassAis required!