Delegates and the Observer Pattern

Why Use Delegates?

Why do we need to use delegates instead of just calling functions directly?

Abstract art representing programming

Delegates solve a fundamental problem in software design: how to allow objects to communicate without creating tight coupling between them. Let's explore why this matters with a practical example.

Consider a game where we want to update the UI when a player takes damage. The direct approach might look like this:

class Player {
public:
  void TakeDamage(int Damage) {
    Health -= Damage;
    UserInterface->UpdateHealthBar(Health);
  }
private:
  UserInterface* UserInterface;
  int Health{100};
};

This creates several problems:

  • Our Player class now needs to know about UI implementation details
  • We can't easily change which UI elements respond to damage
  • Testing becomes harder because we can't separate player logic from UI logic
  • If we want to add new responses to damage (like sound effects), we need to modify the Player class

Using delegates solves these problems by inverting the dependency:

class Player {
 public:
  using DamageDelegate = std::function<
    void(int NewHealth)>;
  void SetOnDamageDelegate(DamageDelegate D) {
    OnDamageDelegate = D;
  }

  void TakeDamage(int Damage) {
    Health -= Damage;
    if (OnDamageDelegate) {
      OnDamageDelegate(Health);  
    }
  }

 private:
  DamageDelegate OnDamageDelegate;
  int Health{100};
};

Now:

  • Player doesn't need to know anything about UI
  • We can add or remove damage responses without touching the Player class
  • Different parts of our program can respond to damage in different ways
  • Testing is easier because we can provide test delegates

This pattern is particularly valuable in game development where systems often need to be loosely coupled but still communicate effectively.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 55 Lessons
  • 100+ Code Samples
  • 91% 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