Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

class — declaring and defining a class

The class keyword declares or defines a class type that can combine data and member functions. Member access and inheritance access default to private, unlike struct, where both default to public.

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

Syntax

class Name;
class Name {
    // members are private by default
public:
    // public interface
};

class introduces a class type. The definition class Name { /* members */ }; describes its members, such as data members and member functions. Defining the type alone does not create an object; the example's declaration Counter counter; creates an object of that type. Remember the semicolon after the closing } in such a standalone definition.

Members of a class defined using class are private by default. A public: label makes subsequent members available without access-control restrictions until another access label or the end of the class. private members can be named by members and friends of the class, but not directly by ordinary external code. In the example, external code uses increment() and value() instead of modifying value_.

Both class and struct define class types; they differ in default member access and default inheritance access: private and public, respectively. Thus, class Derived : Base {}; uses private inheritance; write class Derived : public Base {}; explicitly for public inheritance.

The forward declaration class Name; introduces the name without defining the class. Until a definition is available, the type is incomplete: you can declare pointers or references to it, but cannot define objects of it. In template<class T>, class has a different role: it declares a type parameter, just like typename, and does not restrict the argument to class types.

The example targets C++23 compilation mode. The supplied source is an evolving working draft, not a frozen C++23 edition; this explanation is limited to rules available in C++23. The displayed code was run unchanged in an isolated environment, and its output matched the stated output exactly. Execution in a production environment has not been verified.

Examples

#include <iostream>

class Counter {
    int value_ = 0;

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

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

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