C++ Classes and Objects
A class defines a new type: it lists the data each object holds (attributes, also called data members or fields) and the operations it supports (methods, also called member functions). Once the class exists, you create objects of it just like you create int or string variables.
Defining a class
#include <iostream>
#include <string>
using namespace std;
class Car {
public: // access specifier: members below are usable from outside
string brand;
string model;
int year;
}; // don't forget the semicolon
int main() {
Car car1;
car1.brand = "Volvo";
car1.model = "XC40";
car1.year = 2021;
Car car2;
car2.brand = "Fiat";
car2.model = "500";
car2.year = 2015;
cout << car1.brand << " " << car1.model << " (" << car1.year << ")\n";
cout << car2.brand << " " << car2.model << " (" << car2.year << ")\n";
}Volvo XC40 (2021)
Fiat 500 (2015)
class Car { ... };creates the typeCar.Car car1;creates an object (an instance) of that type.- The dot operator
.accesses an object's members. - Each object has its own copy of the attributes — changing
car2.yeardoes not affectcar1.
Adding behaviour
Classes become interesting when they also contain functions. Inside a method you can use the object's attributes directly:
#include <iostream>
#include <string>
using namespace std;
class Dog {
public:
string name;
int energy = 3;
void bark() {
cout << name << " says Woof!\n";
}
void play() {
if (energy > 0) {
energy--;
cout << name << " plays (energy left: " << energy << ")\n";
} else {
cout << name << " is too tired to play\n";
}
}
};
int main() {
Dog rex;
rex.name = "Rex";
rex.bark();
for (int i = 0; i < 4; i++) {
rex.play();
}
}Rex says Woof!
Rex plays (energy left: 2)
Rex plays (energy left: 1)
Rex plays (energy left: 0)
Rex is too tired to play
class vs struct
In C++ class and struct are almost identical. The only difference is the default access:
| Keyword | Default member access |
|---|---|
struct |
public |
class |
private |
So without public:, the Car above would be unusable from main. By convention, struct is used for plain data bundles and class for types with hidden data and behaviour.
class Secret {
int code = 1234; // private by default
};
Secret s;
s.code = 0; // ERROR: 'int Secret::code' is privateObjects in collections and as parameters
Objects are values: you can store them in arrays and vectors, copy them, and pass them to functions:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Product {
public:
string name;
double price;
int stock;
double stockValue() const {
return price * stock;
}
};
void printProduct(const Product& p) {
cout << p.name << ": " << p.stock << " x " << p.price << " = " << p.stockValue() << "\n";
}
int main() {
vector<Product> inventory = {
{"Pen", 1.5, 100},
{"Notebook", 4.0, 25},
{"Backpack", 35.0, 4}
};
double total = 0;
for (const Product& p : inventory) {
printProduct(p);
total += p.stockValue();
}
cout << "Total stock value: " << total << "\n";
}Pen: 100 x 1.5 = 150
Notebook: 25 x 4 = 100
Backpack: 4 x 35 = 140
Total stock value: 390
The const after stockValue() promises that the method does not change the object, which allows it to be called on a const Product&. The next lesson explains methods in detail.
Tip: Brace initialisation like
{"Pen", 1.5, 100}works here because all members are public and there is no constructor. Real classes usually provide constructors — see the Constructors lesson.
Test yourself
What is the default access level of members in a class?
- public
- private
- protected
- internal
Given Car a; Car b; a.year = 2020;, what is b.year?
- 2020
- Unaffected by a.year
- Always 0
- Compile error
Another name for an object of a class is…
- A method
- An instance
- A namespace
- A template