This is a balance between code organization, compilation speed, and developer convenience. Let's look at when to separate definitions and when to keep them together.
Good candidates for keeping in headers:
Example of appropriate header-only functions:
// Character.h
class Character {
public:
// Simple getter - fine in header
int GetHealth() { return Health; }
// Simple setter - fine in header
void SetName(const std::string& NewName) {
Name = NewName;
}
// Simple calculation - fine in header
bool IsAlive() { return Health > 0; }
private:
int Health{100};
std::string Name;
};
Move functions to CPP files when they:
Example of functions to move:
// Character.h
class Character {
public:
void TakeDamage(int Damage);
void UseHealthPotion(int PotionStrength);
private:
int Health{100};
};
// Character.cpp
#include "Character.h"
// Complex functions often need more headers
#include <algorithm>
void Character::TakeDamage(int Damage) {
// Complex logic belongs in cpp files
if (IsInvulnerable()) { return; }
int ActualDamage =
CalculateDamageReduction(Damage);
Health = std::max(0, Health - ActualDamage);
if (Health <= 0) { OnDeath(); }
}
void Character::UseHealthPotion(
int PotionStrength) {
// Multi-line functions are better in cpp files
if (Health <= 0) { return; }
Health = std::min(
100, Health + PotionStrength);
OnHealthChanged();
}
Consider these factors:
Remember, these are guidelines rather than strict rules. Use your judgment based on your specific needs.
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