🚀 Alguni Start learning

Unit 6: Classes & Objects

Blueprints that look after themselves.

Unit 6 of 8 in C++ for kids. Its 4 lessons are From Struct to Class, Constructors, Keeping Data Safe and Class Master — below is everything each one explains, and a question or two from it to try.

Every sample on this page was compiled and run with g++ before it shipped, and prints exactly what it says it prints.

This unit opens with a fortnight’s trial of everything — no card needed — or with a family plan, bought in the iPhone app. The first two units of every track are free for ever. Try it in the app.

📘 From Struct to Class

A class is a struct with the door closed

A class is the same idea as a struct, except everything starts hidden. public: opens up whatever comes after it — which is why a class almost always begins with that line.

C++

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

class Dog {
public:
    string name;
    int age;

    void speak() {
        cout << name << " says woof" << endl;
    }
};

int main() {
    Dog d;
    d.name = "Rex";
    d.age = 4;
    d.speak();
    return 0;
}

It prints

Rex says woof

The class is the plan, the object is the thing

One class, as many objects as you like — and each keeps its own values.

C++

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

class Dog {
public:
    string name;
    void speak() { cout << name << " woofs" << endl; }
};

int main() {
    Dog a;
    Dog b;
    a.name = "Rex";
    b.name = "Bo";
    a.speak();
    b.speak();
    return 0;
}

It prints

Rex woofs
Bo woofs

Methods that work something out

A method can return a value just like any other function.

C++

#include <iostream>
using namespace std;

class Rect {
public:
    int width;
    int height;

    int area() { return width * height; }
};

int main() {
    Rect r;
    r.width = 3;
    r.height = 5;
    cout << r.area() << endl;
    return 0;
}

It prints

15

Try it yourself

What is the only real difference between a class and a struct in C++?

  • A class is faster
  • A class hides its members by default; a struct shows them
  • Only a class can have methods
  • There is no difference at all

Answer it in the app

🏗️ Constructors

Setting an object up as it is made

A constructor is a method with the same name as the class and no return type. It runs the moment an object is built, which means no more setting every member by hand.

C++

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

class Dog {
public:
    string name;
    int age;

    Dog(string n, int a) {
        name = n;
        age = a;
    }

    void speak() { cout << name << " is " << age << endl; }
};

int main() {
    Dog d("Rex", 4);
    d.speak();
    return 0;
}

It prints

Rex is 4

A constructor with no arguments

Useful for sensible starting values, so an object is never half-built.

C++

#include <iostream>
using namespace std;

class Counter {
public:
    int count;

    Counter() { count = 0; }

    void bump() { count = count + 1; }
};

int main() {
    Counter c;
    c.bump();
    c.bump();
    cout << c.count << endl;
    return 0;
}

It prints

2

More than one constructor

A class may have several, as long as they take different values. C++ picks whichever matches the way you built the object.

C++

#include <iostream>
using namespace std;

class Box {
public:
    int width;
    int height;

    Box() {
        width = 1;
        height = 1;
    }

    Box(int w, int h) {
        width = w;
        height = h;
    }

    int area() { return width * height; }
};

int main() {
    Box small;
    Box big(3, 4);
    cout << small.area() << " " << big.area() << endl;
    return 0;
}

It prints

1 12

this points at the object being worked on

When a parameter shares a name with a member, this-> says which one you mean. It is a pointer to the object the method was called on.

C++

#include <iostream>
using namespace std;

class Point {
public:
    int x;

    Point(int x) {
        this->x = x;
    }
};

int main() {
    Point p(7);
    cout << p.x << endl;
    return 0;
}

It prints

7

Try it yourself

What return type does a constructor have?

  • void
  • int
  • The class itself
  • None at all — you write no return type

Answer it in the app

🔒 Keeping Data Safe

private really does refuse

A private member can only be touched by the class's own methods. This is encapsulation, and unlike Python's underscore, C++ genuinely stops you.

C++

#include <iostream>
using namespace std;

class Box {
private:
    int size;

public:
    void setSize(int s) { size = s; }
    int getSize() { return size; }
};

int main() {
    Box b;
    b.setSize(5);
    cout << b.getSize() << endl;
    return 0;
}

It prints

5

The promise a setter can keep

Because nothing else can reach health, this class can guarantee it never drops below zero. That guarantee is impossible if anyone may assign to it.

C++

#include <iostream>
using namespace std;

class Player {
private:
    int health;

public:
    Player() { health = 100; }

    void hurt(int amount) {
        health = health - amount;
        if (health < 0) {
            health = 0;
        }
    }

    int getHealth() { return health; }
};

int main() {
    Player p;
    p.hurt(150);
    cout << p.getHealth() << endl;
    return 0;
}

It prints

0

Getters can work things out

A getter does not have to hand back a stored value — it can calculate one, so the class never keeps two things that could disagree.

C++

#include <iostream>
using namespace std;

class Rect {
private:
    int width;
    int height;

public:
    Rect(int w, int h) {
        width = w;
        height = h;
    }

    int getArea() { return width * height; }
};

int main() {
    Rect r(3, 4);
    cout << r.getArea() << endl;
    return 0;
}

It prints

12

Try it yourself

Why hide a member behind methods at all?

  • It runs faster
  • The class can then promise something — like a size that is never negative
  • It saves memory
  • To make the code longer

Answer it in the app

🏆 Class Master

Try it yourself

What does this print?

C++

#include <iostream>
using namespace std;

class Tally {
public:
    int n;
    Tally() { n = 0; }
    void up() { n = n + 2; }
};

int main() {
    Tally t;
    t.up();
    t.up();
    t.up();
    cout << t.n << endl;
    return 0;
}

Answer it in the app