D
D
Daniil Demidko2015-12-25 08:28:23
C++ / C#
Daniil Demidko, 2015-12-25 08:28:23

Where is the best place to include header files?

For example:
I have a class described in MyClass.h and its implementation in MyClass.cpp
The class description requires only string

//MyClass.h
#pragma once
#include<string>
class MyClass {
public:
 std::string ExampleFunction();
}

But its body in MyClass.cpp can use headers other than string, such as vector.
//MyClass.cpp
#include "MyClass.h"
//Дальше описание тела

So the question is: where is it better to connect these headers - in MyClass.h or in MyClass.cpp ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
teugen, 2015-12-25
@Daniro_San

Here is an example of a good answer.
In short: the inclusions in the header should be as few as possible, while it should include all the headers necessary for the smooth operation of the code described in it.
In your case, if vector is used exclusively in the implementation and does not show itself in any way in the description of blackbox 'a, you need to include it in .cpp

S
Stanislav Makarov, 2015-12-25
@Nipheris

I’ll add to teugen that if you don’t use a class / structure value, but a pointer to it, then instead of including another header, you can insert a class declaration into the header:

#pragma once
class ExampleClass;
class MyClass {
public:
 ExampleClass* ExampleFunction();
};

and include class definitions where there is no way without it - for example, where class methods are called or its instances are created.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question