Lesson 9 of 10

Classes

Goal

Hiding fields with private, constructors and encapsulation

01

Explanation

The fields of a struct are open to any code that can reach the object, so nothing stops hero.hp = -50;. A class is the same idea with one difference: its members are private unless you say otherwise. Whatever is under public: can be used by code outside the class, and whatever is under private: can only be reached by the class's own functions. If you try to reach it from outside, the compiler rejects the code, so the compiler itself enforces the rule.

A constructor is a function with the same name as the class and no return type, and it runs when the object is created, as in Inventory bag(3);. It's the object's first line of defense: the object is valid from the moment it's created, and a negative capacity becomes zero before anyone can use it. A field and a function can't share a name, so by convention a trailing underscore is added to the name of a private field, giving you capacity_ for the field and capacity() for the function.

This is called encapsulation. The rule "the items never exceed the capacity" stays true because the only way to add an item is add, which checks first and returns false instead of breaking the rule. The functions that only read are const, as in the previous lesson. This is how classes are built in game engines: the data is private, and in front of it sit functions that check before they change anything.

02

Your task

Complete the Inventory class, a player's bag with a limited number of slots. It's created with Inventory bag(3), and its capacity becomes zero if the capacity it's given is negative. Make bool add(const std::string& item) add the item and return true if there's room left, and otherwise return false without adding anything. bool has(const std::string& item) const returns whether the item is in the bag, int count() const returns how many items it holds, and int capacity() const returns its capacity. The data in capacity_ and items_ stays private.

Checks

5 checks
  1. A new bag is empty and has the right capacity
  2. add adds the item and returns true, and has finds what was added
  3. add refuses once the bag is full and never goes over the capacity
  4. A negative capacity becomes zero, so nothing fits
  5. has returns false for anything that wasn't added to the bag
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.