On this page
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
- Always declare a
virtual ~Base() = default;on any polymorphic base class—deleting a derived object through aBase*without a virtual destructor is undefined behavior. - Always mark overrides with
overrideso signature mismatches fail at compile time instead of silently hiding the base method.
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
- tuts/cpp/builtins/concepts Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/namespaces Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins Linked here; links to this page; shared tags: #builtins, #cpp, #prog
- tuts/cpp/language_and_raii/templates_concepts_and_polymorphism Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/casts links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/raii_and_destructors Linked here; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/auto shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/c_style_casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/constexpr shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/lambdas shared tags: #builtins, #cpp, #prog, #tier