Intermediate · Classes, constructors and RAII · topic 13 of 42 · 30 min
Classes and objects: data plus behaviour
Explanation
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.
A first class
#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
}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
| Access | Who can use it |
|---|---|
| public | Everyone: this is the interface of the class |
| private | Only the class's own member functions (and friends) |
| protected | The 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.
struct Point {
double x = 0;
double y = 0;
};
Point p{3.0, 4.0};
std::cout << p.x + p.y << '\n'; // 7Splitting a class into .h and .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_; }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 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.
#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
}Practice (0/4 done)
In class Student { int marks; }; what is the access of marks?
Which line does NOT compile? class Counter { public: int get() const { return n; } void inc() { ++n; } private: int n = 0; }; const Counter c;
What is encapsulation?
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Constructors and destructorsClasses, constructors and RAII · same module
- RAII: let objects clean up for youClasses, constructors and RAII · same module
- Copying objects: the rule of three, five and zeroClasses, constructors and RAII · same module
- Classes and objectsJava Programming (Core to Spring Boot) · Classes and objects
- Access modifiers, static members and encapsulationC# and .NET · Classes and objects
- ClassesJavaScript Programming (language in depth) · Scope, this, prototypes and classes
Questions people ask about this
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.
What makes a class field private?Related
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
- 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.
- Module 4 exam: Classes, constructors and RAII · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Operator overloading, inheritance and polymorphism. 42 topics left in the course before the final exam.