Header Files

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!

3D art showing a character in a bar

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.

Answers to questions are automatically generated and may not have been reviewed.

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved