`protected` — C++ Keyword

`protected` — C++ Keyword

The protected keyword in C++: restricts member access to the class and its derived classes.

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.

protected

Declares that members are accessible within the class itself and by derived classes, but not from external code.

Syntax

class Name {
protected:
    // accessible in this class and derived classes
};

class Derived : protected Base { ... };

Example

#include <print>
#include <cmath>

class Shape {
protected:
    double side_;   // accessible in derived classes

public:
    explicit Shape(double s) : side_(s) {}
};

class Square : public Shape {
public:
    explicit Square(double s) : Shape(s) {}

    double area() const {
        return side_ * side_;   // accesses protected member
    }
};

class Circle : public Shape {
public:
    explicit Circle(double r) : Shape(r) {}

    double area() const {
        return std::numbers::pi * side_ * side_;
    }
};

int main() {
    Square sq{4.0};
    std::println("{}", sq.area());   // 16

    Circle c{3.0};
    std::println("{:.4f}", c.area());
}

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