`class` — C++ Keyword

`class` — C++ Keyword

The class keyword in C++: defines a class type with default private member access.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

class

Defines a class type. Members and base classes are private by default (the only difference from struct). Also used as a template type parameter introducer.

Syntax

class Name { member-declarations };
class Name : access-specifier Base { ... };
template <class T> ...      // equivalent to typename in this context

Example

#include <print>
#include <string>

class Person {
public:
    Person(std::string name, int age)
        : name_(std::move(name)), age_(age) {}

    void greet() const {
        std::println("Hi, I'm {} ({})", name_, age_);
    }

private:
    std::string name_;
    int age_;
};

int main() {
    Person p{"Alice", 30};
    p.greet();   // Hi, I'm Alice (30)
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}