Shocky2 Shocky2 - 2 months ago 13
C++ Question

Class member of an undeclared class

How to make this bit of code work, if these two classes are declared in the same ".h" file? How to make it work if they are in the separate ones?

Simple question, but googling didn't help me.

class Container
{
Piece p;
public:
Container() :p(this) {};
};

class Piece
{
Container* cont;
public:
Piece(Container * c) :cont(c) {};
};

Answer Source

Forward declare Container and then define it later on:

class Container;

class Piece
{
    Container* cont;
public:
    Piece(Container * c) :cont(c) {};
};

class Container
{
    Piece p;
public:
    Container() :p(this) {};
};