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.
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);
}
}
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.
Explore how header files and linkers streamline C++ programming, learning to organize and link our code effectively