tags:

views:

97

answers:

2

I have 3 header files in the project: Form1.h - this is header with implementation there, TaskModel.h with TaskModel.cpp, TaskController.h with TaskController.cpp.

There are content of files:

//-----
TaskController.h

#pragma once
#include "TaskModel.h"
..........



//----
Form1.h
#pragma once
#include "TaskModel.h"
#include "TaskController.h"
.........

The problem:

How to make Form1.h to be included to TaskModel.h. When I directly include, Form1.h to TaskModel.h then there are many errors. If to use forward declaration, how to organaize that ?

+3  A: 

You can forward declare classes not header files.

The problem with cyclic dependencies is usually a mark of bad design. Do you want TaskModel.h to include Form1.h? Why is that? Can it be avoided? Couldn't you just include Form1.h into TaskModel.cpp?

For forward declaration do:

// in TaskModel.h

class Form1; // or other classes that are using in TaskModel.h

//... task model code

// in TaskModel.cpp

#include "Form1.h"

Basically what you are doing here is declaring that such classes exist. Then in the cpp file you include them.

Mind however that this has some limitations:

  • you can only use the forward declared classes for simple tasks
  • you cannot pass them to methods per value, you cannot make them members of classes

As a rule of thumb, if the forwarded classes size is needed to compile the given piece of code, you cannot use a forward.

Kornel Kisielewicz
TaskModel includes nothing.
Mishgun_
you are right, include Form1.h into TaskModel.h (TaskModel.cpp ?)
Mishgun_
Well, I have compiled project successfully as you wrote. Thank you.
Mishgun_
@Mishgun_ : glad I could help :)
Kornel Kisielewicz
A: 

I think you are saying that "TaskModel.h" is being included more than once by your module. To avoid this, at the top of "TaskModel.h" you can put:

#ifndef TASK_MODEL_H
#define TASK_MODEL_H

then at the end of the file put:

#endif
RickNotFred
no, I put pragma there.
Mishgun_
Oops, so you did...
RickNotFred