CodeMIRAI
0 XP

Classes and objects

3 min read 4 runnable examples Quiz included

A class is a type you design yourself. It bundles data (what an object knows) with member functions (what it can do). string and vector are classes from the standard library; now you'll write your own.

A first class

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

class Dog {
public:
    string name;
    int age;

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

int main() {
    Dog rex;
    rex.name = "Rex";
    rex.age = 3;
    rex.bark();

    Dog luna;
    luna.name = "Luna";
    luna.bark();

    cout << rex.name << " is " << rex.age << endl;
    return 0;
}
Output
Rex says woof
Luna says woof
Rex is 3
  • The class is the blueprint; rex and luna are objects, each with its own name and age.
  • The dot reaches members: rex.name, rex.bark().
  • Inside bark, name means the name of whichever object bark was called on.
  • The semicolon after the closing brace of a class is required.

Private data, public functions

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

class BankAccount {
private:
    string owner;
    double balance = 0;

public:
    void setOwner(const string& name) { owner = name; }
    string getOwner() const { return owner; }
    double getBalance() const { return balance; }

    bool deposit(double amount) {
        if (amount <= 0) return false;
        balance += amount;
        return true;
    }
    bool withdraw(double amount) {
        if (amount <= 0 || amount > balance) return false;
        balance -= amount;
        return true;
    }
};

int main() {
    BankAccount acc;
    acc.setOwner("Asha");
    acc.deposit(100);
    cout << acc.withdraw(30) << " " << acc.withdraw(500) << endl;
    cout << acc.getOwner() << ": " << acc.getBalance() << endl;
    // acc.balance = 1000000;   // error: 'double BankAccount::balance' is private
    return 0;
}
Output
1 0
Asha: 70

private members can only be used by the class's own functions; public ones by anyone. Keeping balance private means the only way to change it is through deposit and withdraw, which refuse nonsense like a negative deposit. Protecting data this way is called encapsulation.

Functions that only read the object are marked const after their parameter list, like getBalance() const. The compiler then refuses any change to the object inside them, and they can be called on const objects.

Member functions outside the class

C++
#include <iostream>
using namespace std;

class Rectangle {
    double width = 1, height = 1;     // members of a class are private by default
public:
    void resize(double w, double h);
    double area() const;
    double perimeter() const;
};

void Rectangle::resize(double w, double h) {
    if (w > 0 && h > 0) { width = w; height = h; }
}
double Rectangle::area() const { return width * height; }
double Rectangle::perimeter() const { return 2 * (width + height); }

int main() {
    Rectangle r;
    cout << r.area() << endl;
    r.resize(3, 4.5);
    cout << r.area() << " " << r.perimeter() << endl;
    r.resize(-1, 2);                  // refused: the rectangle keeps its size
    cout << r.area() << endl;
    return 0;
}
Output
1
13.5 15
13.5

The class lists its functions; the bodies can come later, named with the class and :: (the scope resolution operator). In bigger programs the class goes in a header file (rectangle.h) and the bodies in rectangle.cpp.

this

C++
#include <iostream>
using namespace std;

class Counter {
    int count = 0;
public:
    Counter& add(int count) {
        this->count += count;     // this->count is the member; count alone is the parameter
        return *this;             // return the object itself, so calls can chain
    }
    int value() const { return count; }
};

int main() {
    Counter c;
    c.add(5).add(10).add(-3);
    cout << c.value() << endl;
    return 0;
}
Output
12

Inside a member function, this is a pointer to the object the function was called on. You need it when a parameter has the same name as a member, and to return the object itself with *this, which is what makes chained calls like c.add(5).add(10) work.

class or struct?

In C++ the two keywords make the same thing. The only difference is the default: members of a struct are public unless you say otherwise, members of a class private.

C++
struct Point { double x, y; };          // x and y are public
class Circle { double radius; };        // radius is private

By convention, struct is used for plain bundles of data and class for types that protect their data.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.