PDA

View Full Version : Forward declaration fails



[?]jNs
27th July 2011, 11:01
Hi guys, I got a little Problem with a forward declaration. It may be solved easily, but I don't find my mistake.

I got a class TrackElement that has exactly the following header file.


#ifndef TRACKELEMENT_H
#define TRACKELEMENT_H

#include <QLabel>

#include "tracktest.h"

class TrackTest;

class TrackElement : public QLabel
{
Q_OBJECT
public:
explicit TrackElement(TrackTest *parent = 0);

private:
TrackTest test;
};

#endif // TRACKELEMENT_H

First, when I didn't use the forward declaration, the constructor had problems with it too, because im using the TrackElement to create TrackTest and vice versa.
With the forward declaration the constructor causes no errors, but my private test variable of type TrackTest does. "field 'test' has incomplete type"

I don't get it why, if I create a new TrackTest file in the TrackElement .cpp-file, there is no error at all.

Thanks for fast answers :)

FelixB
27th July 2011, 11:15
you have TrackTest as member element. Then you have to include the header. When you only have a forward declaration, how should the compiler know the size of TrackTest?

if you insist on forward-declaring TrackTest, use a pointer as member.

edit: fast enough? ;)

stampede
27th July 2011, 11:17
What do you mean by this:

#include "tracktest.h"

class TrackTest;
I assume that TrackTest is defined in tracktest.h, so whats the point of class declaration after including its definition ? When you include tracktest.h, TrackTest is already a known class, so you can just remove the class TrackTest; declaration and all should work ok.
If you want to use forward-declaration, dont include tracktest.h in header file, but in .cpp file, and leave only the class TrackTest; forward declaration in header (and use pointers). The way its done now makes no sense.

[?]jNs
27th July 2011, 11:30
Huh, damn that was very fast :D
Thanks to both of you. Now it works perfectly and I see, that it makes no sense to include it and then make a forward declaration.
In general: is it "better" make forward declarations in the header file and include the .h in the sourcefile? Or should I use this way only if I got problems like the one above?
Thanks again!

stampede
27th July 2011, 11:37
Forward-declaring may reduce compilation time in case when you change the forward-declared class, because only the .cpp files which includes the class header "class.h" will be compiled again. If you include the "class.h" in header "a.h" instead of forward-declaring, then also every file that includes "a.h" will be recompiled (as well as all other files that include "class.h").
Personally, I'm using forward declarations whenever its possible.
---
Of course, using forward declaration forces you to use pointers if you want to use forward-declared class as member, so its up to you when you find it useful.

[?]jNs
27th July 2011, 12:28
Ok, thank you. That was the answer I needed ;)