0

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) {};
};
Shocky2
  • 504
  • 6
  • 24

2 Answers2

2

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) {};
};
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

Forward declaration is what you are looking for.

class Container;

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

If you google you would find more information. See the one below.

When can I use a forward declaration?

9T9
  • 698
  • 2
  • 9
  • 22