Classes and Objects

A struct is usually used for data only. A class groups data together with the functions that work on that data. This is the main idea of object-oriented programming: a type knows what it holds and what it can do.

#include <iostream>
#include <string>
using namespace std;

class Lamp {
public:
    string color;
    bool on = false;

    void toggle() {
        on = !on;
    }

    string state() {
        return on ? "on" : "off";
    }
};

int main() {
    Lamp desk;
    Lamp bed;
    desk.color = "white";
    bed.color = "blue";
    desk.toggle();
    cout << desk.color << ": " << desk.state() << "\n";
    cout << bed.color << ": " << bed.state() << "\n";
    return 0;
}

Output:

white: on
blue: off

Some words to learn here:

  • Lamp is a class. It is the plan that describes every lamp.
  • desk and bed are objects. Each one is a real lamp made from that plan.
  • toggle and state are methods. A method is a function that belongs to a class.

You call a method with a dot, like desk.toggle(). Inside the method, on means the on of the object you called it on. So desk.toggle() changed desk.on to true, and bed.on stayed false. Every object has its own data, and the methods work on that data.

A method can return a value, like any function. state() returns the text "on" or "off".

bool on = false; gives the member a default value, so every new lamp starts switched off. color has no default here, so main sets it.

The public: line means that everything below it can be used from outside the class, for example from main. The Encapsulation lesson shows what changes without it.

You have used classes since the start of the course. string and vector are classes, and name.length() and scores.push_back(92) are method calls. Now you can write your own classes.

In the exercise, finish a Rectangle class whose area method returns the width times the height.