math
math

Reputation: 2022

Should a header file be inserted twice?

I have the following question about including header files. I'm learning about classes and the following question arose:

I was told that the declartion of a class should go into a separate header file, e.g.

//TestClass.hpp

#include <string>

class TestClass{
private:
  void init(); 
public:
  double r;
  double a;
  std::string Type;
  TestClass(const std::string& stringType);
};

in the respective TestClass.cpp I defined everything correctly:

// TestClass.cpp
//

#include "TestClass.hpp" 
#include <string>
#include <iostream>


void TestClass::init()
{ // Initialise all default values
  // Default values
  r = 0.08;
  a = 0.30;
  Type = "Hello";
}

TestClass::TestClass(const std::string& stringType)
{ // Create option type
  init();
  Type = stringType;
  if (Type == "hello")
    Type = "Hello";
}

If I include the directive <string> in the header file, do I have to include it again in the TestClass.cpp file?

Upvotes: 1

Views: 120

Answers (2)

Spook
Spook

Reputation: 25929

No, you don't, but I would do that anyway to make the code more clear: you're explicitly saying then "this code requires string to work properly". If, in the future, you'll decide not to use TestClass.hpp for some reason, the code would stop compiling and you'll have to manually resolve lacking includes.

Remember, that #include does no magic, it simply opens the file you specify and replaces the #include with contents of that file. So you required the file TestClass.hpp to be pasted into TestClass.cpp, but then you required the file string to be pasted into TestClass.hpp. In effect, string will be included in TestClass.cpp as well.

This arises the second problem: you have no include guards in your file. If you #include a file, wich also #includes your TestClass.hpp, you'll get compilation errors. The correctly implemented C++ headers looks more less like the following:

#ifndef TESTCLASS_HPP
#define TESTCLASS_HPP

// Code

#endif

This ensures, that if your file gets included second time, it won't actually be used.

This can also be achieved by using automatic include guard:

#pragma once

However, this is non-standard, so some compilers may refuse to recognize it.

Upvotes: 4

user657267
user657267

Reputation: 21040

No, everything you declare in the header file will be pulled into any file that includes the header. You should add an include guard / #pragma once by the way.

Upvotes: 4

Related Questions