OOP - Week 2, Lecture 1: Classes and Objects
Why Do We Need Classes?
Imagine you need to store two dates. With what you know so far, you would write:
int day1 = 7, month1 = 10, year1 = 2023;
int day2 = 19, month2 = 9, year2 = 2026;
This works for two dates, but it gets messy quickly:
- Nothing connects the variables.
day1,month1andyear1belong together, but C++ sees six separate variables. With 100 dates you would have 300 variables to keep track of. - Functions become awkward. A function that prints a date needs three parameters,
print(int d, int m, int y), and you must pass the right three in the right order every time. - Nothing protects the data. Any line of code can write
month1 = 25;, and the program will happily store a month that does not exist.
A class solves these problems. It lets you create your own type, like Date, that you use the same way you use int or double:
Date d1, d2;

| What a class gives you | What it means for the Date example |
|---|---|
| Grouping | d1 holds its own day, month and year together in one object. |
| Data and functions together | The functions that work on a date live inside Date, so they always receive the right data. |
| Protection | The data is hidden, so it can only change through functions that check the value first. |
| Reuse | You write the class once and create as many objects from it as you need. |
You can think of a class as a blueprint and an object as a thing built from that blueprint. The rest of this lecture shows how to write the blueprint.
1. Class Structure
class ClassName {
private:
DataType privateVar; // data member
public:
DataType publicVar; // data member
ReturnType functionName(parameters) { // member function
// ...
}
}; // a class ends with a semicolon
- Data members are the variables declared inside the class.
- Member functions are the functions declared inside the class.
- Do not forget the
;after the closing brace.
If you do not write an access specifier, the members of a class are private by default.
2. Access Specifiers
An access specifier decides who is allowed to use a member.
| Specifier | Who can access it |
|---|---|
private | Only the member functions of the same class. Code outside the class cannot use it. |
public | Everyone: the member functions, main, and any other code that has an object of the class. |
protected | The member functions of the same class, and the member functions of derived classes (we will meet inheritance in Week 6). Code outside the class cannot use it. Until then, it behaves like private. |
class Example {
private:
int a; // only Example's own member functions can use a
protected:
int b; // Example's functions, and derived classes
public:
int c; // anyone
};
The usual rule: make the data members private and the member functions public. Outside code then has to go through the public functions to reach the data.

3. Setters and Getters
Data members are private, so code outside the class cannot read or change them directly. The class gives that code public member functions to do it instead:
| Feature | Setter | Getter |
|---|---|---|
| Purpose | Changes the value of a private data member | Returns the value of a private data member |
| Name | setName | getName |
| Parameters | The new value | None |
| Return type | Usually void | The type of the data member |
| Can check the value first | Yes (validation) | Not needed |
class Rectangle {
int width; // private by default
public:
void setWidth(int w) { // setter
if (w > 0) { // only accept a valid width
width = w;
}
}
int getWidth() { // getter
return width;
}
};
Rectangle r;
r.setWidth(5);
cout << r.getWidth(); // 5
r.setWidth(-3); // rejected by the setter, width is still 5
A data member that has a getter but no setter can be read from outside the class but never changed from outside.
4. Example: The Date Class
Here is a Date class with three private data members and a public function to set each one. Each function checks the value before it stores it, so an invalid value is ignored.
class Date {
int day, month, year; // private by default
public:
void setDay(int d) {
if (d < 1 || d > 31) { // validation
return;
}
day = d;
}
void setMonth(int m) {
if (m < 1 || m > 12) { // validation
return;
}
month = m;
}
void setYear(int y) {
if (y < 1) { // validation
return;
}
year = y;
}
};
setDay, setMonth and setYear are setters. The check on the day is simple: it accepts any day from 1 to 31, even 31 in February. Checking the length of each month is possible, but we do not need it here.
5. Defining an Object
A class is a blueprint. To use it, create an object (also called an instance) of that class:
ClassName objName;
Use the dot operator . to call a public member function:
Date d;
d.setYear(2026);
d.setMonth(2);
Accessing a private data member from outside the class is an error.
d.day = 5;does not compile, becausedayis private. You will see an error like βdayis a private member ofDateβ. The exact words depend on your compiler.
6. Class Scope and Accessing Class Members
The data members and member functions declared inside a class belong to the scope of that class. Where you are in the code decides how you reach them.
Inside the class, a member function uses the data members by their plain names, with no object and no dot. It works on the object that called it:
class Date {
int day; // data member
public:
void setDay(int d) { day = d; } // uses day directly
int getDay() { return day; }
};
Outside the class, you must go through an object, with the dot operator, and only the public members are available:
Date a, b;
a.setDay(7); // a's own day becomes 7
b.setDay(19); // b's own day becomes 19
cout << a.getDay() << " " << b.getDay(); // 7 19
- Every object has its own copy of the data members. Calling
a.setDay(5)never changes the day ofb. The member functions are the same for all objects, and each call works on the object in front of the dot. - Names inside a class do not clash with names elsewhere. Two different classes can both have a member called
day. - A parameter or a local variable with the same name hides the member. If
setDayhad a parameter namedday, thenday = day;would assign the parameter to itself and never touch the member. That is why we name the parametersd,mandy. - With a pointer to an object, you use
->instead of the dot. We will meet that in Week 5.
7. Encapsulation
Encapsulation means putting the data and the functions that work on it together in one class, and hiding the data so it can only be reached through the classβs public functions.
Why we use it:
- Protects the data. The setter can refuse an invalid value, so month
13is never stored through it. (A new object still starts with garbage until we meet constructors in Lecture 2.) - Controls access. If a member only has a getter and no setter, outside code can read it but not change it.
- Lets you change the inside later. Code that uses the class only depends on the public functions, so you can change how the data is stored without breaking that code.
- Makes bugs easier to find. The data can only change inside the classβs own functions.
A getter lets outside code read a private member:
int getYear() {
return year;
}
Why is
return year;not an error, ifyearis private? Private means private to code outside the class.getYearis a member function ofDate, so it is allowed to use every member ofDate, private ones included. The caller only receives a copy of the value, never the variable itself.
8. Putting It Together
A complete program: a Date class with private data, public setters and getters, and a main that creates three objects. The first is set to 7/10/2023, the second to 19/9/2026, and the third is never set. Each date is printed on its own line.
#include <iostream>
using namespace std;
class Date {
private:
int day, month, year;
public:
void setDay(int d) {
if (d < 1 || d > 31) // validation
return;
day = d;
}
void setMonth(int m) {
if (m < 1 || m > 12) // validation
return;
month = m;
}
void setYear(int y) {
if (y < 1) // validation
return;
year = y;
}
int getDay() {
return day;
}
int getMonth() {
return month;
}
int getYear() {
return year; // inside the class, private data is accessible
}
};
int main() {
Date d1, d2, d3;
d1.setDay(7);
d1.setMonth(10);
d1.setYear(2023);
d2.setDay(19);
d2.setMonth(9);
d2.setYear(2026);
// d3 is never set
cout << d1.getDay() << "/" << d1.getMonth() << "/" << d1.getYear() << endl;
cout << d2.getDay() << "/" << d2.getMonth() << "/" << d2.getYear() << endl;
cout << d3.getDay() << "/" << d3.getMonth() << "/" << d3.getYear() << endl;
return 0;
}Read the output line by line (you can click each output line in the terminal to jump to the code that printed it):
d1andd2print the dates we stored in them.d3was never set, so its data members were never given a value. They hold whatever was left in memory, so the numbers printed are garbage. They are unpredictable: they may be zeros or any other numbers, and they can change from one run to the next.
Reading a variable that was never given a value is a bug. A class should never let this happen. Constructors, which come next, fix it by giving every object valid values when it is created.