Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ include header problem

Tags:

c++

I am new to c/c++, I am confused about followings:

  1. Whether I should put class declarations in its own header file, and actual implementation in another file?
  2. Whether I should put headers like <iostream> in the example.h file or in example.cpp file?
  3. If all the classes need to use <iostream>, and I include a class's header file into another class's header, does it mean I included <iostream> twice?
  4. If I use a lot STL classes, what is a good practice to use std::?
like image 482
Rn2dy Avatar asked Feb 07 '11 01:02

Rn2dy


2 Answers

1.Whether I should put class declarations in its own header file, and actual implementation in another file?

You can write the definition of a class, and the definition of the members of the class separately in the same header file if you are manipulating templates. Also, if you want to make your members function inline, you can define them inside the class definition itself. In any other case, it is better to separate the definition of the class (.hpp file) and the definition of the members of the class (.cpp).

2.Whether I should put headers like in the example.h file or in example.cpp file?

It Depends on if you need those headers in the example.h file or in your .cpp file only.

3.If all the classes need to use , and I include a class's header file into another class's header, does it mean I included twice?

It happens if you don't wrap your class definitions by the following macros:

#ifndef FOO_HPP
#define FOO_HPP
class { 
...
};
#endif

5.If I use a lot STL classes, what is a good practice to use std::?

I think it is better whenever you can to use std:: each time instead of using namespace std. This way you will use only the namespaces that you need and your code will be more readable because you will avoid namespace conflicts (imagine two methods that have the same name and belong to two different namespaces).

But most importantly where is question number 4 anyway?

like image 99
Amokrane Chentir Avatar answered Sep 18 '22 12:09

Amokrane Chentir


  1. Generally, yes. It helps with organization. However, on small projects it may not be that big of a deal.

  2. I'm having trouble understanding the question here. If you're asking where to put the #include directive, the implementation file should include the header file.

  3. Yes, but the use of include guards prevents multiple inclusions.

like image 45
Maxpm Avatar answered Sep 21 '22 12:09

Maxpm