Video Coming Soon...

Created by Zed A. Shaw Updated 2026-06-19 17:00:40

45: Pointers and new

In this exercise you'll learn about using new to create the Combatant struct on the heap, the difference between the heap and stack, and using delete to clean up these structs when you're done. I'll have to mention that this isn't really what you should do, but knowing this will help with understanding shared_ptr.

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

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};
  Combatant* player = new Combatant{"Player", 20, 50};
  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.