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?
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.
When to Keep Definitions in Headers
Good candidates for keeping in headers:
- One-line functions
- Simple getters and setters
- Template functions (these usually must be in headers)
- Heavily inlined functions for performance
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;
};
When to Move to CPP Files
Move functions to CPP files when they:
- Have complex logic
- Might change frequently
- Use many external dependencies
- Are several lines long
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();
}
Guidelines
Consider these factors:
- Will changing this function require recompiling many files?
- Is the function so simple that separating it makes code harder to follow?
- Would other developers expect to see this implementation in the header?
- Does the function use many headers that would otherwise not be needed?
Remember, these are guidelines rather than strict rules. Use your judgment based on your specific needs.
Header Files
Explore how header files and linkers streamline C++ programming, learning to organize and link our code effectively