Video Coming Soon...

Created by Zed A. Shaw Updated 2026-04-30 02:05:52

45: Pointers and new

This exercise is pending. Quick notes about this exercise:

The Code

View Source file ex45.cpp Only

#include <fmt/core.h>
#include <string>
#include <random>

std::random_device RNG;
std::mt19937 GENERATOR(RNG());

struct Combatant {
  std::string name;
  int damage{0};
  int hp{0};
  float hearing_distance{0.0f};
};

int random_number(int from, int to) {
  std::uniform_int_distribution rand(from, to);
  return rand(GENERATOR);
}

void fight(Combatant* attacker, Combatant* defender) {
  int damage = random_number(0, attacker->damage);

  if(damage > 0) {
    defender->hp -= damage;
    fmt::println("{} hit {} for {}. {} now has {} hp",
        attacker->name, defender->name, damage,
        defender->name, defender->hp);
  } else {
    fmt::println("{} missed {}!",
        attacker->name, defender->name);
  }

  if(defender->hp <= 0) {
    fmt::println("{} died. {} wins! {} has {} HP",
        defender->name, attacker->name,
        attacker->name, attacker->hp);
  }
}

int main(int argc, char* argv[]) {
  Combatant* giant_rat = new Combatant{"Giant Rat", 20, 30, 2.4f};
  Combatant* player = new Combatant{"Player", 20, 50, 1.4f};
  bool player_turn = false;

  while(giant_rat->hp > 0 && player->hp > 0) {
    if(player_turn) {
      fight(giant_rat, player);
    } else {
      fight(player, giant_rat);
    }

    player_turn = !player_turn;
  }

  delete player;
  delete giant_rat;
}

The Breakdown

line of code
Description.

The Discussion

Blah blah.

Further Study

Previous Lesson Next Lesson

Register for Learn C++ the Hard Way

Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.