Header Files

Multiple Classes Per Header

Can I declare multiple classes in one header file? When should I do this?

3D art showing a character in a bar

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.

When to Group Classes

Good reasons to put multiple classes in one header:

  • Small helper classes that are only used by the main class
  • Closely related classes that always work together
  • A set of classes that form a cohesive feature

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);
};

When to Separate Classes

You should create separate header files when:

  • Classes are used independently
  • Classes are large or complex
  • Classes might be reused in different contexts
  • Different teams work on different classes

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;
  }
};

Guidelines

Consider these factors:

  • Will other developers expect to find these classes together?
  • Does it make sense to reuse one class without the others?
  • Would separating the files make the code harder to understand?
  • Is the header file getting too large to manage easily?

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.

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