How to include the same class in multiple files?

3

Because I can not include the same class in multiple files like this:

#include "familia.h"
class pessoa{

private:
familia *f;
};

-----
#include "pessoa."

class familia{
private:
pessoa *p;
};
    
asked by anonymous 20.04.2016 / 07:57

1 answer

4

You are having problems because they are interdependent. You need to make sure one does not call the other indefinitely. You need to ensure that the class declaration exists (you do not need to declare all of it, but have it declared explicitly):

#ifndef PESSOA_H
#define PESSOA_H
class Familia;
class Pessoa {
    Familia *f;
};
#endif

And then

#ifndef FAMILIA_H
#define FAMILIA_H
class Pessoa;
class Familia {
    Pessoa *p;
};
#endif

This is called forward declaration .

Do not forget to put guards in .cpp to not load headers in duplicate.

    
20.04.2016 / 12:07