Tutorials / C++: From Basics to Modern C++ / Structs and classes: your own types

Structs and classes: your own types

15 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. 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

  1. Write a Temperature class that stores degrees Celsius privately and has methods celsius(), fahrenheit() and setCelsius(double), rejecting values below -273.15.
  2. Make a vector of Student and sort it by mark using std::sort with a lambda comparing two students.
  3. Add an enum class Grade and a function that turns a mark into a grade.
cpp
#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