Yes, you can declare multiple classes in one header file! While the convention is one class per file, there are good reasons to group related classes together.
Good reasons to put multiple classes in one header:
Here's an example:
// Inventory.h
#pragma once
class Item {
public:
virtual int GetValue() = 0;
};
class InventorySlot {
Item* StoredItem{nullptr};
int Quantity{0};
public:
void Store(Item* NewItem) {
StoredItem = NewItem;
Quantity = 1;
}
Item* GetItem() { return StoredItem; }
};
class Inventory {
static const int MaxSlots{20};
InventorySlot Slots[MaxSlots];
public:
bool AddItem(Item* NewItem);
Item* GetItem(int SlotIndex);
};
You should create separate header files when:
Example of when to separate:
// Weapon.h
#pragma once
class Weapon {
int Damage{10};
public:
int GetDamage() { return Damage; }
};
// Character.h
#pragma once
#include "Weapon.h"
class Character {
Weapon* EquippedWeapon{nullptr};
public:
void EquipWeapon(Weapon* NewWeapon) {
EquippedWeapon = NewWeapon;
}
};
Consider these factors:
Remember, these are guidelines, not strict rules. Use your judgment based on your specific situation.
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