C++ Keywords Reference#
This post consolidates core C++ and Modern C++ (C++11+) keywords, organized by role.
Anatomy of Keyword Placement in a Function Declaration#
Keywords attached to a C++ function declaration are placed into Declaration Specifiers (prefix) / Function Qualifiers & Specifiers (after ()) / Function Body (at the end) according to the C++ grammar and compiler parsing order:
virtual const int& FUNCTION(PARAM_TYPE PARAM_NAME) const & noexcept = 0;
─────── ────────── ─────────────────────────────── ──────────────── ───
│ │ │ │ └─ Function Body: { ... }, = default, = delete, = 0
│ │ │ └─ Function Qualifiers & Specifiers: const/volatile, &/&&, noexcept, override, final
│ │ └─ Function Name(Params)
│ └─ Return Type (prefix const = const return value)
└─ Declaration Specifiers: explicit, virtual, inline, static, constexpr- 1. Declaration Specifiers (before function:
explicit,virtual,inline,static,constexpr):- Declare how the function is linked, inlined, or invoked before reaching the function name, independent of its parameters or body.
- 2. Function Qualifiers & Specifiers (after
():const/volatile,&/&&,noexcept,override,final):- Avoiding Return-Type Ambiguity (
const,&/&&): Writingconstor&/&&in front (const int& func()) qualifies the return type, not the member function. Placing them after()unambiguously qualifies the implicit*thisobject’s constness (const) and value category (&= lvalue,&&= rvalue) (see Copy Elision & Move Semantics: Ref-qualified Member Functions). - Referencing Parameter Scope (
noexcept): The compiler parses left-to-right, and conditional exception specificationsnoexcept(expr)must be able to reference parameter names (e.g.,void f(T x) noexcept(x.is_safe())). Thus,noexceptmust appear after the parameter list( ... )has been declared.
- Avoiding Return-Type Ambiguity (
- 3. Function Body & Pure Specifier (at the end after
=:= default,= delete,= 0):- Replacing
{ ... }: These stand directly in place of the function body{ ... }at the very end of the declaration. - Why
=is used: Following the classic pure virtual syntax (= 0), C++11 reused existing keywords (defaultfromswitchanddeletefrom memory deallocation) after=to avoid introducing new reserved words while clearly signaling a special function-body definition.
- Replacing
1. Special Member Function & Conversion Control Keywords (= default, = delete, explicit, noexcept)#
These keywords control constructors, destructors, copy/move operations, and type conversions at compile time (see Copy Control and Copy Elision & Move Semantics).
| Keyword | Target | Meaning & Core Role |
|---|---|---|
= default | Default constructor & the 5 copy-control special member functions | Explicitly instructs the compiler to generate the synthesized default implementation (memberwise initialization/copy/move/destruction). Implicitly inline when written on the in-class declaration. |
= delete | Any function (primarily copy constructor & copy assignment) | Prohibits calling the function at compile time. Used for non-copyable types like std::unique_ptr and std::iostream. |
explicit | Single-argument constructors or conversion operators (operator TYPE(), e.g., operator int(), operator bool()) | Blocks unintended implicit type conversions and copy initialization (=), allowing only direct initialization (CLASS x(val);) and explicit casts (static_cast).(Exception: explicit operator bool() const blocks arithmetic conversions but is still automatically applied in condition contexts like if, while, !, &&, ||, and ?:.) |
noexcept | Move constructor, move assignment, destructor, ordinary functions | Guarantees to the compiler and standard library that the function will never throw an exception. If an exception escapes a noexcept function, std::terminate() is called immediately without stack unwinding.(For its role in conditional move optimization across standard containers and algorithms, see Copy Elision & Move Semantics) |
class Resource {
public:
Resource() = default; // Use synthesized default constructor
explicit Resource(int size); // Disallow implicit int -> Resource conversion (Resource r = 10; is an error!)
Resource(const Resource&) = delete; // No copy constructor
Resource& operator=(const Resource&) = delete; // No copy assignment
Resource(Resource&&) noexcept = default; // Non-throwing move constructor
Resource& operator=(Resource&&) noexcept = default;// Non-throwing move assignment
explicit operator bool() const noexcept { // Auto-converts to bool only in condition contexts like if (res)
return valid_;
}
~Resource() = default;
private:
bool valid_ = false;
};2. Inheritance & Polymorphism (OOP) Keywords (virtual, = 0, override, final)#
These keywords govern runtime dynamic binding and overriding rules in inheritance hierarchies (see Object-Oriented Programming).
| Keyword / Specifier | Placement | Meaning & Core Role |
|---|---|---|
virtual | Before a base-class non-static member function or destructor | Enables runtime dynamic binding when called through a base pointer (Base*) or reference (Base&), dispatching to the derived implementation matching the runtime Dynamic Type (without virtual, defining a same-named function in Derived merely causes Name Hiding rather than overriding, so calling through Base* always invokes Base’s version).⚠️ Polymorphic base classes must declare their destructor virtual (virtual ~Base()) to prevent derived memory leaks on delete basePtr;. |
= 0(Pure Virtual) | Immediately before the semicolon (;) of a virtual declaration | Declares a Pure Virtual Function with no required base implementation. Any class with one or more pure virtual functions becomes an Abstract Base Class (ABC) that cannot be instantiated directly. |
override | After the parameter list (and const) of a derived virtual function | Explicitly states that this function overrides a base virtual function. Emits an immediate compile error if the signature does not match the base virtual function. |
final | After a class name (class D final) or after a virtual function (void f() override final;) | On a class: seals the class against any further inheritance. On a virtual function: prohibits further derived classes from overriding that function. |
class Shape { // Abstract Base Class, cannot be instantiated directly
public:
virtual ~Shape() = default; // Essential virtual destructor
virtual double area() const = 0; // '= 0': pure virtual function
};
class Circle : public Shape {
public:
explicit Circle(double r) : radius_(r) {}
double area() const override final { // 'final' on function: subclasses of Circle cannot override area()!
return 3.1415926535 * radius_ * radius_;
}
private:
double radius_;
};
class UnitCircle final : public Circle { // 'final' on class: UnitCircle itself cannot be inherited from!
public:
UnitCircle() : Circle(1.0) {}
// double area() const override; // Compile error! Circle::area() is marked final
};3. Constness, Optimization Control & Compile-Time Keywords (const, volatile, constexpr, mutable)#
These keywords control mutability, compiler optimization suppression, and compile-time constant evaluation (see Variables and Basic Types and Classes).
| Keyword | Target | Meaning & Core Role |
|---|---|---|
const | Variables, pointers/references, return types (const T& f()), after member function () (void f() const) | 1. Variables/Pointers: Prevents modification after initialization (see Top-Level vs. Low-Level const). 2. Function Return Type ( const T& f()): Written before the function name to qualify the return type, preventing callers from mutating the underlying data through a returned reference or pointer.3. Const Member Function ( void f() const): Written after () to make the implicit this pointer const CLASS* const, preventing member mutation and allowing the function to be called on both non-const and const objects. |
volatile | Variables, pointers/references (volatile int* p), after member function parameter list | 1. Prevents Compiler Optimization: Indicates that the memory can change asynchronously outside normal program flow (e.g., memory-mapped hardware registers or OS signal handlers), forcing every read/write to go directly to memory without register caching or elision (forms the cv-qualifiers alongside const).2. Warning (Not for Threading): Unlike Java/C#, C++ volatile guarantees neither atomicity nor CPU memory ordering (memory barriers). Always use std::atomic or a mutex for inter-thread communication. |
constexpr | Variables & functions (constexpr int sq(int x)) | Instructs the compiler to verify that a variable or function can be evaluated at compile time as a constant expression. |
mutable | Class data members or value-capturing lambdas ([v]() mutable) | 1. Class Data Member: Allows a member (e.g., access counter, cache, mutex) to be modified even inside a const member function or on a const object.2. Lambda Expression: Allows modifying by-value captured copies inside the lambda body (which is operator() const by default). |
class Screen {
public:
void display() const { // const member function: ordinary members cannot be modified
++access_ctr_; // OK! mutable member can be modified even inside a const member function
}
private:
mutable int access_ctr_ = 0;
};4. Type Deduction Keywords (auto, decltype)#
These keywords instruct the compiler to deduce types from expressions (see Variables and Basic Types and Expressions).
| Keyword | Deduction Basis | Core Deduction Rules |
|---|---|---|
auto | Deduced from the initializer value | Strips references (&) and top-level const by default. Write const auto& explicitly when you want to bind by reference without copying or preserve top-level constness. |
decltype(expr) | Deduced from the declared type or value category of expr (without evaluating expr) | Preserves top-level const and references by returning the exact declared type for unparenthesized variable names, or a type matching the expression’s value category (lvalue → T&, xvalue → T&&, prvalue → T) for all other expressions.(For the two-step deduction rules, see Expressions: decltype) |
5. Lifetime, Linkage & Encapsulation Keywords (static, extern, inline, friend)#
These keywords control object lifetime, cross-file linkage, inlining, and private member access (see Functions and Classes).
| Keyword | Context | Meaning & Core Role |
|---|---|---|
static | 1. Local variable inside a function 2. Class data/function member 3. File-scope variable/function | 1. Local static object: Initialized once on first execution and persists until program termination.2. Class static member: Shared by all instances of the class rather than stored per object. static member functions have no this pointer and cannot be declared const.3. File-scope static: Restricts visibility to the current translation unit (Internal Linkage; see Namespaces for a comparison with anonymous namespaces). |
extern | Variable declaration (extern int x;) | Declares a global variable or extern const constant defined in another translation unit without allocating storage (not a definition). |
inline | Function declarations/definitions & constexpr functions | Requests inline expansion at call sites to avoid call overhead, and permits placing function definitions in header files (.h) without triggering multiple-definition linker errors (ODR violations). |
friend | Inside a class body (granting access to a nonmember function or class) | Grants a nonmember function (e.g., operator<<, operator+) or another class direct access to private and protected members. Friendship is neither inherited nor transitive. |