Lesson 8 of 10

Structs

Goal

A struct with its fields and member functions

01

Explanation

A struct groups related data under one name. A player has a name and health, so instead of defining two separate variables for every player, you write struct Player { std::string name; int hp = 100; };, and don't forget the semicolon after the closing brace. You create a player by listing the values in the order of the fields, like Player hero{"Layan", 80};, and any field you leave out takes its default value, so the player Player hero{"Layan"}; has 100 HP. You reach the fields with a dot, as in hero.hp -= 10;.

You can also write functions inside the struct that work on its fields directly. These are called member functions: inside takeDamage, hp means this player's own health, and you call it with a dot, as in hero.takeDamage(30);. The word const after the parentheses in bool alive() const is a promise that the function doesn't change the object, and on a const Player& you can only call functions that make this promise. So a function that reads the team as const std::vector<Player>& can't call alive() unless it's const.

The benefit is that the rule stays with the data: health never drops below zero, because damage goes through takeDamage, which prevents it. But the fields of a struct are exposed, and nothing stops code outside it from writing hero.hp = -50;. That's what the next lesson deals with.

02

Your task

Complete Player so its health starts at 100 when it isn't given, and make void takeDamage(int amount) reduce the health without ever taking it below zero, ignoring negative damage so it never adds health. Make bool alive() const return true as long as the health is above zero. Then complete int aliveCount(const std::vector<Player>& team) so it returns how many players on the team are alive.

Checks

5 checks
  1. A Player can be created from a name and has 100 HP if none is given
  2. takeDamage reduces the health
  3. takeDamage never takes the health below zero, and negative damage doesn't raise it
  4. alive returns true as long as the health is above zero
  5. aliveCount counts the players on the team who are alive
03

Hints

0/3
Track lessons0 of 10 done

C++ is the language behind game engines, browsers and operating systems, because it's fast and gives you full control.

Beginner level, 10 lessons, 2 hours in total.

main.cpp
OutputC++17 (GCC 9, Judge0)

Compiling and running your code on the server.

–/5

Compiling and running your code on the server.

5 checks listed under “Your task”.

Track lessons0 of 10 done

C++ is the language behind game engines, browsers and operating systems, because it's fast and gives you full control.

Beginner level, 10 lessons, 2 hours in total.