`public` — C++ Keyword

`public` — C++ Keyword

The public keyword in C++: grants unrestricted access to class members.

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.

public

Declares that the following class members are accessible from anywhere. Also specifies public inheritance when inheriting from a base class.

Syntax

class Name {
public:
    // accessible everywhere
};

class Derived : public Base { ... };

Example

#include <print>

class Rectangle {
public:
    Rectangle(double w, double h) : w_(w), h_(h) {}

    double area() const { return w_ * h_; }   // public method

private:
    double w_, h_;
};

class Square : public Rectangle {
public:
    explicit Square(double s) : Rectangle(s, s) {}
};

int main() {
    Rectangle r{3.0, 4.0};
    std::println("{}", r.area());   // 12

    Square s{5.0};
    std::println("{}", s.area());   // 25
}

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;
}