Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

private — private member access and inheritance

The private keyword restricts access to class members to the class's members and friends. In a base clause, it specifies private inheritance. This is a program correctness check, not a memory-security boundary.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

class C {
private:
    int value;
public:
    int get() const { return value; }
};

class Derived : private Base {};

private: gives subsequent member declarations private access until the next access specifier or the end of the class definition. It applies to data members, member functions, nested types, and other members. Members of the class and its friends declared with friend can access private members; ordinary external code cannot name them directly.

Member access defaults to private in class and public in struct and union. Permission belongs to the class, not an individual object: a member function can read a private field of another object of the same class. A derived class does not automatically gain access to its base class's private members.

In class Derived : private Base {};, private specifies inheritance accessibility rather than starting a member section. Public and protected members of Base are accessible as private members of Derived; private members of Base remain directly inaccessible to Derived without additional permission. Ordinary external code cannot implicitly convert Derived* to Base* through that private base. Omitting the inheritance access specifier means private for class and public for struct.

In the example, public increment() and get() provide operations on private value. The program is expected to print 2 followed by a newline. Uncommenting counter.value = 10; produces an access violation requiring a diagnostic. private supports encapsulation, not encryption or memory protection. This description targets C++23; the supplied source is an evolving draft, not a frozen C++23 publication.

Examples

#include <iostream>

class Counter {
private:
    int value = 0;

public:
    void increment() { ++value; }
    int get() const { return value; }
};

int main() {
    Counter counter;
    counter.increment();
    counter.increment();
    std::cout << counter.get() << '\n';
    // counter.value = 10;
}

Result

2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources