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:
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:
public
, private
) apply to each memberLet'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;
}
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.
Explore how header files and linkers streamline C++ programming, learning to organize and link our code effectively