Header Files

Circular Dependencies

Can I have circular dependencies if I use pointers? I noticed the lesson showed a Character with a Sword pointer, and a Sword with a Character pointer. How does that work?

3D art showing a character in a bar

Yes, you can have circular dependencies when using pointers! This is one of the main reasons we use pointers in C++. Let's break down how and why this works.

Why Pointers Are Special

When we use a pointer, the compiler only needs to know that the type exists - it doesn't need to know the full details of the type. This is because all pointers have the same size in memory, regardless of what they point to.

Here's a working example:

// Sword.h
#pragma once
class Character;// Forward declaration

class Sword {
public:
  void SetWielder(Character* NewWielder);
  Character* GetWielder() { return Wielder; }
private:
  Character* Wielder{nullptr};
  int Damage{10};
};
// Character.h
#pragma once
class Sword;// Forward declaration

class Character {
public:
  void EquipWeapon(Sword* NewWeapon);
  Sword* GetWeapon() { return Weapon; }
private:
  Sword* Weapon{nullptr};
  int Health{100};
};
// Character.cpp
#include "Character.h"
#include "Sword.h"// Full header needed here

void Character::EquipWeapon(Sword* NewWeapon) {
  if (Weapon) {
    // Tell old weapon it's no longer equipped
    Weapon->SetWielder(nullptr);
  }
  Weapon = NewWeapon;
  if (NewWeapon) {
    // Tell new weapon who is wielding it
    NewWeapon->SetWielder(this);
  }
}

Why It Doesn't Work Without Pointers

If we tried to use actual objects instead of pointers, we'd have a problem:

class Sword {
  // Not a pointer!
  Character Wielder;
};
class Character {
  // Not a pointer!
  Sword Weapon;
};
error: incomplete type 'Character' used in nested name specifier
error: incomplete type 'Sword' used in nested name specifier

This fails because to create a Character, we need to know how big a Sword is. But to know how big a Sword is, we need to know how big a Character is! It's a chicken-and-egg problem that pointers solve for us.

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