-1

I have three classes:
BaseClass, that contains ElementClass as field
ElementClass, that contains BaseClass as field and ChildClass as return type (pointer)
ChildClass, that's inherits from BaseClass.
When I'm trying to compile this, I am getting
expected class-name before '{' token
for ChildClass, that was included in ElementClass, that was included in BaseClass.
I understand, why is this happens. Because I'm trying to inherit child class from nonexistent, for compiler, class BaseClass.
I can't understand hot to fix this. Thank you.

Here is code example with this problem
BaseClass.h

#ifndef INHERITTEST_BASECLASS_H
#define INHERITTEST_BASECLASS_H

#include "ElementClass.h"

class ElementClass;

class BaseClass
{

private:
    ElementClass *m_someField;
};


#endif


ElementClass.h

#ifndef INHERITTEST_ELEMENTCLASS_H
#define INHERITTEST_ELEMENTCLASS_H

#include "ChildClass.h"

class ChildClass;

class ElementClass
{
private:
    ChildClass *m_class;
};


#endif


ChildClass.h

#ifndef INHERITTEST_CHILDCLASS_H
#define INHERITTEST_CHILDCLASS_H

#include "BaseClass.h"

class ChildClass : public BaseClass
{

};


#endif
Megaxela
  • 97
  • 8

1 Answers1

0

BaseClass, that contains ElementClass as field

ElementClass, that contains BaseClass as field

So, a BaseClass instance contains an ElementClass instance which contains a BaseClass instance which contains an ElementClass instance which contains... instances all the way down. One instance is going to use all of your memory and then some. That cannot work.

It also cannot work because when defining the first class, you need to have a complete definition of the second class, which needs a complete definition of the first class, which wasn't defined yet.

You must use indirection. At least one of the classes must not contain the other instance inside, but instead a pointer or a reference to an instance.

Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • I tried to answer by quoting my own answer inside itself. You beat me to the punch. I'm stil copy-pasting... – bolov Mar 16 '16 at 17:42