Structs and classes: your own types
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- Final project: a command-line expense tracker
Why make your own types
Suppose you track students with three parallel vectors: names, ages and marks. Sort one and the others are out of step. A single type that holds all three fields fixes that and gives you a place to put the rules about them. That is the core of object-oriented design: data and the code that protects it, in one unit.
struct: a bundle of fields
#include <iostream>
#include <string>
#include <vector>
struct Student {
std::string name;
int age{};
double mark{};
};
int main() {
Student s1{"Asha", 20, 88.5};
Student s2{.name = "Bilal", .age = 21, .mark = 74.0}; // C++20 designated init
std::vector<Student> cls{s1, s2};
for (const auto& s : cls) {
std::cout << s.name << " (" << s.age << "): " << s.mark << "\n";
}
}
Fields are accessed with the dot operator. Through a pointer you use the arrow: p->name means (*p).name. The {} after age and mark gives them a default value of zero. Without that, a default-constructed Student would have junk in those fields. Make a habit of giving every field a default.
Adding behaviour
A struct can also have functions. These member functions can use the fields directly.
struct Rectangle {
double width{};
double height{};
double area() const { return width * height; }
bool isSquare() const { return width == height; }
};
// Rectangle r{3, 4}; r.area() == 12
The word const after the parameter list promises that the function does not change the object. A const method can be called on a const object; a non-const one cannot. Mark every method that only reads as const. It is one of the cheapest ways to catch mistakes.
class and access control
The only technical difference between struct and class is the default access: struct members are public by default, class members are private. By convention, I use struct for plain data and class when the type has rules to protect.
#include <iostream>
#include <stdexcept>
class BankAccount {
public:
explicit BankAccount(double opening) : balance_{opening} {
if (opening < 0) throw std::invalid_argument("negative opening balance");
}
void deposit(double amount) {
if (amount <= 0) throw std::invalid_argument("deposit must be positive");
balance_ += amount;
}
bool withdraw(double amount) {
if (amount <= 0 || amount > balance_) return false;
balance_ -= amount;
return true;
}
double balance() const { return balance_; }
private:
double balance_;
};
int main() {
BankAccount acc{100.0};
acc.deposit(50);
acc.withdraw(30);
std::cout << acc.balance() << "\n"; // 120
// acc.balance_ = 1e9; // error: balance_ is private
}
This is the point of private. Nobody outside can set the balance to a nonsense value, because the only ways to change it go through functions that check the rules. When a bug appears, you know the culprit is inside these few lines.
A few details in that code. The trailing underscore on balance_ is a naming habit of mine to separate fields from parameters; pick a convention and stay with it. The part after the colon, balance_{opening}, is the member initialiser list. It sets fields before the constructor body runs, and the next lesson explains why that matters. explicit stops the compiler converting a plain double into a BankAccount by accident.
Splitting a class across files
The class definition goes in a header and the member function bodies in a .cpp file, using ClassName:: before the function name.
// circle.h
#pragma once
class Circle {
public:
explicit Circle(double r);
double area() const;
private:
double radius_;
};
// circle.cpp
#include "circle.h"
#include <numbers>
Circle::Circle(double r) : radius_{r} {}
double Circle::area() const { return std::numbers::pi * radius_ * radius_; }
Short methods can stay in the class body, where they are implicitly inline.
enum class
For a fixed set of named choices, use a scoped enumeration.
enum class Status { Pending, Shipped, Delivered };
Status s = Status::Shipped;
if (s == Status::Delivered) { /* ... */ }
Names are scoped, so Pending will not collide with another enum's Pending, and values do not silently convert to integers. The old unscoped enum does both, which is why I avoid it.
The common mistake
Making every field public "to keep it simple". It is simple until a second person changes a field in a way you never planned. The opposite mistake is adding a getter and setter for every field, which is just a public field with extra typing. Expose operations that make sense for the type, such as deposit, not raw access to its guts.
Try it yourself
- Write a
Temperatureclass that stores degrees Celsius privately and has methodscelsius(),fahrenheit()andsetCelsius(double), rejecting values below -273.15. - Make a vector of
Studentand sort it by mark usingstd::sortwith a lambda comparing two students. - Add an
enum class Gradeand a function that turns a mark into a grade.
#include <iostream>
#include <string>
#include <vector>
struct Student {
std::string name;
int age{};
double mark{};
};
int main() {
Student s1{"Asha", 20, 88.5};
Student s2{.name = "Bilal", .age = 21, .mark = 74.0}; // C++20 designated init
std::vector<Student> cls{s1, s2};
for (const auto& s : cls) {
std::cout << s.name << " (" << s.age << "): " << s.mark << "\n";
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account