Skip to content

Intermediate · Classes, constructors and RAII · topic 13 of 42 · 30 min

Classes and objects: data plus behaviour

Explanation

A class is a blueprint that bundles data (member variables) with the functions that work on it (member functions). An object is one thing made from that blueprint. private members can only be used inside the class, which protects the data; public members are the class's interface.

Why classes?

So far, data and functions lived separately. A bank account has a balance AND rules: you cannot withdraw more than you have, deposits must be positive. If the balance is a plain variable, any code anywhere can set it to -5000 by mistake. A class keeps the data and its rules together and controls who can touch the data. This idea is called encapsulation.

Think of it like this: A class is like the design of an ATM. Every ATM made from that design (every object) has its own cash inside, but customers can only use the buttons on the front (public functions). The cash box (private data) is locked; only the machine's own logic opens it.

A first class

cpp
#include <iostream>
#include <string>

class BankAccount {
public:
    void deposit(long long paise) {
        if (paise > 0) balance_ += paise;
    }
    bool withdraw(long long paise) {
        if (paise <= 0 || paise > balance_) return false;
        balance_ -= paise;
        return true;
    }
    long long balance() const { return balance_; }

private:
    long long balance_ = 0;   // only member functions can touch this
};

int main() {
    BankAccount acc;              // an object
    acc.deposit(50000);
    std::cout << acc.withdraw(80000) << '\n';   // 0: refused
    std::cout << acc.balance() << '\n';         // 50000
    // acc.balance_ = -1;   // error: balance_ is private
}
Data is private; the public functions enforce the rules. The trailing underscore is a common naming habit for members.

Member functions and the dot operator

Functions written inside a class are member functions (often called methods). You call them on an object with a dot: acc.deposit(500). Inside a member function, the class's members are used directly by name. Behind the scenes, each member function receives a hidden pointer called this, which points to the object it was called on, so balance_ really means this->balance_.

const member functions

long long balance() const promises that the function does not change the object. You can call const functions on const objects (for example on a const BankAccount& parameter). Mark every function that only reads as const; the compiler then stops accidental changes and your class works with const references.

public, private and protected

AccessWho can use it
publicEveryone: this is the interface of the class
privateOnly the class's own member functions (and friends)
protectedThe class and classes derived from it (see the inheritance topic)

struct versus class

In C++, struct and class are almost the same thing. The only difference is the default access: members of a struct are public by default, members of a class are private by default. By convention, use struct for simple bundles of data with no rules (like a Point with x and y) and class when there are rules to protect.

cpp
struct Point {
    double x = 0;
    double y = 0;
};

Point p{3.0, 4.0};
std::cout << p.x + p.y << '\n';   // 7
A plain struct with public data, created with brace initialisation.

Splitting a class into .h and .cpp

cpp
// account.h
#pragma once
class BankAccount {
public:
    void deposit(long long paise);
    long long balance() const;
private:
    long long balance_ = 0;
};

// account.cpp
#include "account.h"
void BankAccount::deposit(long long paise) {
    if (paise > 0) balance_ += paise;
}
long long BankAccount::balance() const { return balance_; }
ClassName:: in front of the function name says "this is the deposit that belongs to BankAccount".

Static members

A static member belongs to the class itself, not to each object. A static counter, for example, can count how many accounts were opened. Since C++17 you can write inline static int count = 0; inside the class.

Common mistakes

  • Forgetting the semicolon after the closing brace of a class: class A { }; — the ; is required.
  • Making all data public "to make it easy", which loses the protection classes give.
  • Forgetting const on getters, then getting errors when calling them through a const reference.
  • Writing getters and setters for every field automatically. Expose operations that make sense (deposit, withdraw), not raw fields.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Classes and objects: data plus behaviour · 1/6

Classes and objects

Classes bundle data with the functions that work on it. This is the heart of object oriented programming.

Prefer a video by a teacher? Find free videos on “c++ classes objects encapsulation public private tutorial” on YouTube ↗

In real life: A shopping cart in an e-commerce app

An online store keeps each user's cart as an object. Items can only be added through addItem, which refuses a quantity of zero or less, and the total is calculated by the class itself. No other part of the app can put a negative quantity in the cart, because the item list is private.

cpp
#include <iostream>
#include <string>
#include <vector>

class Cart {
public:
    bool addItem(const std::string& name, int pricePaise, int qty) {
        if (qty <= 0 || pricePaise < 0) return false;
        items_.push_back({name, pricePaise, qty});
        return true;
    }
    long long totalPaise() const {
        long long sum = 0;
        for (const auto& it : items_) sum += 1LL * it.pricePaise * it.qty;
        return sum;
    }
private:
    struct Item { std::string name; int pricePaise; int qty; };
    std::vector<Item> items_;
};

int main() {
    Cart cart;
    cart.addItem("Notebook", 6000, 3);
    cart.addItem("Pen", 1000, 0);           // refused
    std::cout << cart.totalPaise() / 100 << '\n';   // 180
}
The rules live inside the class, so every caller follows them.

Practice (0/4 done)

Task 1 · Question

In class Student { int marks; }; what is the access of marks?

Task 2 · Question

Which line does NOT compile? class Counter { public: int get() const { return n; } void inc() { ++n; } private: int n = 0; }; const Counter c;

Task 3 · Question

What is encapsulation?

Task 4 · Practice

Design a class Rectangle with private width and height (doubles), a function setSize(w, h) that refuses negative values, and const functions area() and perimeter(). Create two rectangles in main and print their areas.

Quick quiz

Question 1

1.What is the only difference between struct and class in C++?

Question 2

2.What does const after a member function's brackets mean?

Question 3

3.What is this inside a member function?

Question 4

4.How do you define a member function outside the class?

Question 5

5.A static member variable is…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

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

Answer: Default member access: public for struct, private for class

Everything else, including functions and inheritance, works the same.

What does const after a member function's brackets mean?

Answer: It promises not to change the object

A const member function can be called on const objects and cannot modify members.

What is this inside a member function?

Answer: A pointer to the object the function was called on

this points to the current object; members are accessed through it.

How do you define a member function outside the class?

Answer: void BankAccount::deposit(long long p) { }

ClassName:: ties the definition to the class.

A static member variable is…

Answer: shared by the whole class, one copy in total

Static members belong to the class, not to individual objects.

Two objects of the same class…Related

Answer: Each have their own copies of instance fields

Instance fields belong to each object.

From Classes and objects

How do you call a static method Fare on class MetroCard?Related

Answer: MetroCard.Fare(3)

Static members are reached through the class name.

From Access modifiers, static members and encapsulation

What makes a class field private?Related

Answer: A leading #

#name fields are truly private; _name is only a naming convention.

From Classes

What is the difference between a class and an object?Related

Answer: A class is the blueprint; an object is one thing made from it

One class can make many objects, each with its own data.

From Classes and objects

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Classes, constructors and RAII” before its exam: Constructors and destructors, RAII: let objects clean up for you, Copying objects: the rule of three, five and zero.
  2. Module 4 exam: Classes, constructors and RAII · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Operator overloading, inheritance and polymorphism. 42 topics left in the course before the final exam.

← Previous: Text: C strings and std::string