Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "class ClassName;" mean when put in header file of other class definition?

Tags:

c++

qt

I am a bit confused about this line of code class TreeItem;. class TreeItem; is defined in other files not included in this file. I would must look this question up in a book, but I am sure answer for this question is very simple.

#ifndef TREEMODEL_H
#define TREEMODEL_H

#include <QAbstractItemModel>
#include <QModelIndex>
#include <QVariant>

class TreeItem; //here, what does this do??

//! [0]
class TreeModel : public QAbstractItemModel
{
   ...
public:
   ...
private:
   ...
};
//! [2]

#endif // TREEMODEL_H
like image 298
Coaxial Avatar asked Jul 06 '15 10:07

Coaxial


1 Answers

It is a forward declaration, and it is useful to enable to have pointers to TreeItem-s in some internal structures, etc.

Forward declarations are notably needed when you have co-recursive definitions; e.g. a struct foo containing pointers to struct bar which contains pointers to struct foo, etc... You might even declare these struct-s and define the functions operating on them in different translations units.

It is common practice, both in C and in C++, to forward declare some struct (or class) and to have variables which are pointers to it, and declare (and possibly call) functions handing such pointers.

Of course, some other file (or translation unit) would declare such opaque data structures and implement operations on it.

This is a common way to implement abstract data types.

BTW, there generally is a very common example of that in standard C. The FILE type from <stdio.h> is quite often some opaque (or at least, well hidden by many header files) struct (and you obviously don't need to know the internals of it to use <stdio.h> functions like fprintf)

In your (Qt's) case, you don't want to #include <QTreeItem> -or whatever header file is declaring class TreeItem- in this QTreeModel header file. If you did, that would add an additional header dependency (you don't need to recompile TreeModel code when TreeItem implementation has changed!) and would slow down compilation.

In smaller software projects, you might simply have a single header file and define all the struct inside.

like image 118
Basile Starynkevitch Avatar answered Oct 05 '22 23:10

Basile Starynkevitch