Including Headers in CPP Files

Why do we need to include the header file in its own cpp file? The cpp file already has all the class code!

This is a common source of confusion! Even though the CPP file contains the implementations of our class functions, we still need to include the header. Here's why:

The Compiler Needs the Class Definition

When we define member functions in a CPP file, we need to tell the compiler these functions belong to our class. The compiler needs to know:

  • What class these functions belong to
  • What member variables exist in the class
  • What access specifiers (public, private) apply to each member

Let's see what happens if we don't include the header:

// Character.cpp
void Character::TakeDamage(int Damage) {
  Health -= Damage;
}
error: 'Character' has not been declared
error: 'Health' was not declared in this scope

Here's the correct way:

// Character.h
class Character {
public:
  void TakeDamage(int Damage);
private:
  int Health{100};
};
// Character.cpp
#include "Character.h"

void Character::TakeDamage(int Damage) {
  Health -= Damage;
}

It Helps Catch Errors

Including the header also helps us catch errors. If our implementation doesn't match the declaration in the header, we'll get a compiler error. For example:

// Character.h
class Character {
public:
  void TakeDamage(int Damage);
};
// Character.cpp
#include "Character.h"

void Character::TakeDamage(float Damage) {
  Health -= Damage;
}
error: parameter type mismatch
note: previous declaration was 'void Character::TakeDamage(int)'

This helps us maintain consistency between our header and implementation files.

Header Files

Explore how header files and linkers streamline C++ programming, learning to organize and link our code effectively

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Header File Syntax: <> vs ""
Why do some header files use angle brackets (<>) while others use quotes ("")?
Circular Dependencies
Can I have circular dependencies if I use pointers? I noticed the lesson showed a Character with a Sword pointer, and a Sword with a Character pointer. How does that work?
Header File Locations
How does the compiler know where to find my header files? What if they are in different folders?
Understanding #pragma once
Why do we need #pragma once? What does it do exactly?
Multiple Classes Per Header
Can I declare multiple classes in one header file? When should I do this?
Separating Declarations
Should I always move function definitions to cpp files? The lesson mentioned small functions can stay in the header - how do I decide?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant