Classes

Programming Languages · C++ Going Further · 14 min

Design your own types with fields, methods and constructors, and make objects from them.

Your own type

A class is a blueprint for your own type. It bundles related variables, called fields. public: lets code outside the class use them. Each thing you make from a class is an object:

class Dog {
public:
    std::string name;
    int age;
};

Dog d;
d.name = "Rex";

Don't forget the ; after the class's closing brace!

  • Above main, write a class Book with public fields std::string title and int pages.

  • In main, make a Book b, set its title to "Dune" and its pages to 412.

  • Print Dune has 412 pages using b.title and b.pages.

Methods: functions inside a class

A method is a function that lives inside a class. It can use the object's fields directly. Call it with a dot:

class Dog {
public:
    std::string name;
    void bark() {
        std::cout << name << " says woof\n";
    }
};

d.bark();
  • Inside Book, add a method void describe() that prints the title, : , the pages and pages.

  • In main, call b.describe().

Constructors

A constructor is a special method that runs when an object is made. It has the class's name and no return type. Use it to fill in the fields in one go:

class Dog {
public:
    std::string name;
    Dog(std::string n) {
        name = n;
    }
};

Dog d("Rex");
  • Add a constructor Book(std::string t, int p) that sets title and pages.

  • In main, create Book b("Dune", 412); and call b.describe().

Many objects, one class

One class can make as many objects as you like. Each object keeps its own fields, so changing one book never touches another. That's the whole point of a blueprint.

  • Create a second Book called h for "The Hobbit" with 310 pages.

  • Call describe() on h too.

Put it together: bank account

Finish a tiny BankAccount class. It already has an owner, a balance and a constructor. Give it two methods, then try it out.

  • Add a method void deposit(int amount) that adds amount to balance.

  • Add a method void show() that prints the owner, : , then the balance.

  • In main, make an account for "Ada" with 100, deposit 50, then call show().

More in C++ Going Further

Previous: References & Pointers · Next: Inheritance and Polymorphism