On this page
  1. Classes, Inheritance & virtual
  2. Overview
  3. Notes & Pitfalls
  4. Example

Classes, Inheritance & virtual

Prev: Concepts (C++20) | Up: builtins | Next: Namespaces
Rel: RAII & Destructors, Templates, Concepts & Polymorphism
Ref: cppreference — Classes
Tags: #public #prog #cpp #builtins #oop #tier/standard


Overview

In C++, struct (default public members/inheritance) and class (default private members/inheritance) are otherwise identical. Dynamic polymorphism is opt-in via virtual methods and vtables—you only pay for indirection when you ask for it.

Notes & Pitfalls

Example

#include <cassert>
#include <memory>

struct Shape {
    virtual ~Shape() = default;
    virtual int area() const = 0;
};

struct Square final : Shape {
    int side;
    explicit Square(int s) : side(s) {}
    int area() const override { return side * side; }
};

int main() {
    std::unique_ptr<Shape> s = std::make_unique<Square>(4);
    assert(s->area() == 16);
}

Linked from

Related notes