Classes and OOP

Classes and OOP

Classes, structs, access control, inheritance, virtual functions, and object design.

Classes and OOP

Class basics

class Rectangle {
public:
    Rectangle(double w, double h) : width_{w}, height_{h} {}
    double area() const { return width_ * height_; }

private:
    double width_{};
    double height_{};
};

struct vs class

Special member functions

Inheritance

class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const = 0;
};

class Circle : public Shape {
public:
    explicit Circle(double r) : radius_{r} {}
    double area() const override { return 3.14159 * radius_ * radius_; }

private:
    double radius_{};
};

Keywords to know

Best-practice reminders

Rule of zero and rule of five

class SocketOwner {
public:
    SocketOwner(SocketOwner&&) noexcept = default;
    SocketOwner& operator=(SocketOwner&&) noexcept = default;

    SocketOwner(const SocketOwner&) = delete;
    SocketOwner& operator=(const SocketOwner&) = delete;
};

Modern class features

struct Config {
    std::string host;
    int port{};
    auto operator<=>(const Config&) const = default;
};

Polymorphism alternatives