c++ Recursive headers for abstract classes

330 views Asked by At

Let's say I want to compile something like this:

//Prova.h:
//--------------------
#ifndef _PROVA_
#define _PROVA_

#include "Terza.h"

class Prova{
public:
 Prova();

};
#endif

and

//Terza.h:
//--------------------
#ifndef _TERZA_
#define _TERZA_

#include "EreProva.h"

class Terza{
public:
  Terza();
};
#endif

and

//EreProva.h:
//--------------------
#ifndef _EREPROVA_
#define _EREPROVA_

#include "Prova.h"

class EreProva : public Prova{
  public:
  EreProva();
};
#endif

which doesn't compile saying "'Prova' : base class undefined".

What is the best way to avoid recursion of header between inherited classes?

3

There are 3 answers

0
AudioBubble On

Sometimes you can work around problems of this sort by tring the following: (1) try adding the "#pragma once" directive at the top of your files, although this may be compiler specific (I used it when developing in VC++ some time ago) (2) instead of including the header files in the class, you can try just add "class Prova", or whatever class it is, to indicate a class which you will define later on but want to "use" now.

Although as Als says, it is better to avoid such designs.

3
Alok Save On

If you need to have cyclic dependencies there is something wrong with your design and you should revisit your design and try to remove such complex and unwanted cyclic dependencies.

One of overcoming cyclic dependencies is to use Forward Declarations, but note that once you forward declare a type the type becomes Incomplete type for the compiler and there are limitations about what operations you can do with it. You cannot perform any operations on that type instances which need the compiler to know the memory layout of the type.

Good Read:
When can I use a forward declaration?

3
John Dibling On

In this code:

//Prova.h:
//--------------------
#ifndef _PROVA_
#define _PROVA_

#include "Terza.h"

class Prova{
public:
 Prova();

};

Since you don't use the Tezra class in any way, you don't need the #include. Take it out. Also, you are missing and #endif. Close the #ifndef in this file with a matching #endif in this file.

Moreover:

//Terza.h:
//--------------------
#ifndef _TERZA_
#define _TERZA_

#include "EreProva.h"

class Terza{
public:
  Terza();
};
#endif

#endif

You also don't use the EreProva class in this file at all -- so take out the #include statement. You also have an extra #endif at the end of the file. There is only one #ifndef here, so there should only be one #endif. Take the last one out.