Classes and Objects
GOALBuild a structure with rules that protects its own data.
A class is a struct with rules. Anyone can put anything in a struct — including a score of -50. Hiding the data in a class means it only changes through the routes you allow. For contest problems a struct is usually enough; this lesson is here for the Cambridge syllabus and for the two lessons that follow.
ON THIS PAGE
//THE EXAMPLE
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int score;
public:
void set(string n, int s) {
name = n;
if (s < 0) s = 0;
if (s > 100) s = 100;
score = s;
}
int get() {
return score;
}
};
int main() {
Student a;
a.set("Bat", 150);
cout << a.get() << endl;
a.set("Bat", 72);
cout << a.get() << endl;
return 0;
}100 72
//LINE BY LINE
Watch it run
Student a; is made. Neither field can be seen from outside.
struct or class?
In C++ there is exactly one difference: a struct starts public and a class starts private. Everything else is the same — a struct can have methods and constructors too.
| What you need | Use |
|---|---|
| Хэдэн талбарыг хамт барих / Hold a few fields together | struct |
| Утгыг хамгаалах дүрэмтэй / Rules that protect the value | class |
| Тэмцээний код / Contest code | Бараг үргэлж struct / almost always struct |
In a contest a struct is shorter and can be built with {a, b} directly. Writing a class where you need no protection is just more typing.
When NOT to make one
A class is for fields that belong TOGETHER. Bundling unrelated things can feel tidy and makes the code harder to read.
| Situation | What to do |
|---|---|
| Оюутны нэр, оноо, анги / A student's name, score, class | Нэг бүтэц / one type — they travel together |
| Ганц утга / A single value | Энгийн хувьсагч / just a variable |
| Нэг л удаа хэрэглэх хоёр тоо / Two numbers used once | Хос / a pair or tuple |
| «Бүх юмаа хийх» бүтэц / A "holds everything" type | Хэсэг болгон салга / split it up |
A quick test: if you change one field, must another change with it? If so, they belong together. If not, they probably do not.