Why declare the class that you included as the header file?

Why declare the class that you included as the header file?

#include "TreeCallObj.h"
#include "TreeDevObj.h"
#include "TreeDevCallObj.h"

class TreeCallObj; //what is the purpose of this line ?
class TreeDevObj;  //what is the purpose of this line ?
class TreeDevCallObj;  //what is the purpose of this line ?


class Apple
{
public:
...
private:
...
}
+5
source share
8 answers

Consider this:

//a.h
#ifndef A_H
#define A_H

#include "b.h"
class A
{
   B* b;
};
#endif

//b.h
#ifndef B_H
#define B_H

#include "a.h"
class B
{
   A* a;
};
#endif

Now you try to turn on one of the files in the other, say #include "a.h".

The compiler will analyze it as:

#ifndef A_H
#define A_H

fine - A_Hnot defined

#include "b.h"

try pasting the contents:

#ifndef B_H
#define B_H

ok since B_Hnot defined

#include "a.h"

it will not determine A, because it is A_Hdetermined. So we have

class B
{
   A* a;
};

which will result in an error because it has Anot been defined or not declared before use.

The forward declaration corrects this.

Of course, the best solution for this is to not include it at all (unless you need to).

+6
source

?

. .

, @Luchian Grigore, , - - .

+5

, , forward declaration .

+3

. , , .

+1

.

: - :

class Foo;

struct Gizmo
{
    void f(Foo);
};

, , , :

#include "Foo.hpp"

class Foo;

struct Gizmo
{
    void f(Foo);
    Foo x;
};

...

+1

, - . . , , , , .

, .

+1

, . , ( ) . . - , .

+1

If your header files are correct, I don't see the point in the declaration, because they should already be declared in the header

0
source

All Articles