A class joins data and the functions that work with that data into one unit – a template from which objects are made. This lesson covers attributes and methods, constructors, public and private parts (encapsulation) and operator overloading, using a fraction and a bank account as examples.
Before you start: prior knowledge you need – STL, structures. How to learn: retype and run every example, and solve the tasks at the end on your own first; open the hint and the solution only after that. All programs are in C++ (C++17); they have been checked to compile and give the output shown.
From a structure to a class
A structure (struct) groups data – see Structures and unions. A class (class) adds methods and access control. The only difference between the keywords: in a struct everything is public by default, and in a class it is private.
#include <iostream>
#include <string>
using namespace std;
class Rectangle {
public: // accessible to everyone
double a, b; // attributes (data)
double area() const { // a method; const = it does not change the object
return a * b;
}
double perimeter() const {
return 2 * (a + b);
}
};
int main() {
Rectangle r; // an object of the class Rectangle
cin >> r.a >> r.b;
cout << "Area = " << r.area() << ", Perimeter = " << r.perimeter() << "\n";
return 0;
}
For the input 3 4 the program prints:
Area = 12, Perimeter = 14
Constructors and encapsulation
A constructor is a special method with the same name as the class; it is called when an object is created and sets its initial state. Data that must not be changed from outside goes into private – it is changed only through methods that check the rules. This is called encapsulation.
#include <iostream>
#include <string>
using namespace std;
class Account {
private:
string owner;
long long balance; // cannot be changed directly from outside
public:
Account(string name, long long initial) : owner(name), balance(initial) {} // constructor
void deposit(long long amount) {
if (amount > 0) balance += amount;
}
bool withdraw(long long amount) { // returns whether it succeeded
if (amount <= 0 || amount > balance) return false;
balance -= amount;
return true;
}
long long getBalance() const { return balance; }
string getOwner() const { return owner; }
};
int main() {
Account acc("Ana", 1000);
int q;
cin >> q;
while (q--) {
string op;
long long x;
cin >> op >> x;
if (op == "deposit") acc.deposit(x);
else if (!acc.withdraw(x)) cout << "rejected: " << x << "\n";
}
cout << acc.getOwner() << " has " << acc.getBalance() << "\n";
// acc.balance = 1000000; // COMPILE ERROR: balance is private
return 0;
}
For the input below (3 operations) the program prints:
3
deposit 500
withdraw 2000
withdraw 300
rejected: 2000
Ana has 1200
The notation : owner(name), balance(initial) is the initializer list – the recommended way for a constructor to set the attributes. Methods that only read are marked with const.
Operator overloading: the Fraction class
#include <iostream>
#include <numeric> // gcd
using namespace std;
class Fraction {
long long num, den; // numerator, denominator (private by default)
void reduce() {
long long g = gcd(num, den);
num /= g; den /= g;
if (den < 0) { num = -num; den = -den; } // the denominator is always positive
}
public:
Fraction(long long n = 0, long long d = 1) : num(n), den(d) { reduce(); }
Fraction operator+(const Fraction& o) const { return Fraction(num * o.den + o.num * den, den * o.den); }
Fraction operator*(const Fraction& o) const { return Fraction(num * o.num, den * o.den); }
bool operator<(const Fraction& o) const { return num * o.den < o.num * den; }
friend ostream& operator<<(ostream& out, const Fraction& f) { // printing with cout <<
return out << f.num << "/" << f.den;
}
};
int main() {
long long a, b, c, d;
cin >> a >> b >> c >> d;
Fraction x(a, b), y(c, d);
cout << x << " + " << y << " = " << x + y << "\n";
cout << x << " * " << y << " = " << x * y << "\n";
cout << (x < y ? "the first is smaller" : "the first is not smaller") << "\n";
return 0;
}
For the input 1 2 2 6 the program prints:
1/2 + 1/3 = 5/6
1/2 * 1/3 = 1/6
the first is not smaller
When a class has operator<, its objects can be sorted with sort and stored in a set without a separate comparator. The function gcd comes from the header <numeric> (C++17).
A vector of objects
#include <bits/stdc++.h>
using namespace std;
class Student {
public:
string name;
vector<int> grades;
Student(string n) : name(n) {}
double average() const {
if (grades.empty()) return 0;
return accumulate(grades.begin(), grades.end(), 0.0) / grades.size();
}
};
int main() {
int n;
cin >> n;
vector<Student> schoolClass;
for (int k = 0; k < n; k++) {
string name;
int m;
cin >> name >> m;
Student s(name);
for (int j = 0; j < m; j++) { int g; cin >> g; s.grades.push_back(g); }
schoolClass.push_back(s);
}
const Student* best = &schoolClass[0];
for (const auto& s : schoolClass)
if (s.average() > best->average()) best = &s;
cout << fixed << setprecision(2) << best->name << " " << best->average() << "\n";
return 0;
}
For the input below the program prints the student with the best average:
3
Ana 3 5 4 5
Marko 2 3 4
Jelena 4 5 5 5 4
Jelena 4.75
Practice tasks
Every task has an example, a hint and a solution. The solutions have been checked on the examples in the text.
TASK 01Difficulty: easy
The Point class
Write a class Point with the coordinates x, y, a constructor and the method distance(const Point& p). Read n points and print the perimeter of the (closed) polygon they form in that order, to two decimal places.
Example
Input
4
0 0
3 0
3 4
0 4
Output
14.00
Hint
The perimeter is the sum of the distances between point i and point (i+1) % n. Distance: sqrt(dx*dx + dy*dy) or hypot(dx, dy).
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
class Point {
public:
double x, y;
Point(double x = 0, double y = 0) : x(x), y(y) {}
double distance(const Point& p) const { return hypot(x - p.x, y - p.y); }
};
int main() {
int n;
cin >> n;
vector<Point> pts(n);
for (auto& p : pts) cin >> p.x >> p.y;
double perimeter = 0;
for (int i = 0; i < n; i++) perimeter += pts[i].distance(pts[(i + 1) % n]);
cout << fixed << setprecision(2) << perimeter << "\n";
return 0;
}
TASK 02Difficulty: medium
Stopwatch
Make a class Time (hours, minutes, seconds) with a constructor from the total number of seconds, the operator + and printing in the form hh:mm:ss (with leading zeros). Read n times (hh mm ss) and print their sum; the hours may go over 24.
Example
Input
3
01 30 45
00 45 30
10 00 00
Output
12:16:15
Hint
Inside the class keep only the total number of seconds; compute the hours, minutes and seconds when printing. Leading zeros: setw(2) << setfill('0').
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
class Time {
long long s; // total seconds
public:
Time(long long sec = 0) : s(sec) {}
Time(int h, int m, int sec) : s(h * 3600LL + m * 60 + sec) {}
Time operator+(const Time& o) const { return Time(s + o.s); }
friend ostream& operator<<(ostream& out, const Time& t) {
return out << setfill('0') << setw(2) << t.s / 3600 << ":"
<< setw(2) << t.s / 60 % 60 << ":" << setw(2) << t.s % 60;
}
};
int main() {
int n;
cin >> n;
Time total;
for (int i = 0; i < n; i++) {
int h, m, s;
cin >> h >> m >> s;
total = total + Time(h, m, s);
}
cout << total << "\n";
return 0;
}
Common mistakes and tips
Do not forget the semicolon after the closing brace of a class: class A { ... };.
If you write your own constructor with parameters, the default one (without parameters) no longer exists – vector<MyClass> v(n) then does not work, unless the parameters have default values.
Pass objects bigger than a couple of numbers to functions as const MyClass& – without copying.
Check your knowledge
Open the quiz
Classes and objects
1. What is the default access to members in a class?
2. When is a constructor called?
3. What does const after a method mean, e.g. double area() const?
4. What does operator< in a class make possible?
Podešavanja kolačića
Koristimo kolačiće da bismo vam pružili najbolje moguće iskustvo. Takođe nam omogućavaju da analiziramo ponašanje korisnika kako bismo stalno poboljšavali veb lokaciju za vas.