C++ Classes and Objects: Your First Class, Constructor, and Methods
Three calls to increment print hits=3. The same guide shows why a const member must be initialized in the constructor list, why a const method cannot change a member, and what the compiler says when main touches a private member.
Written November 11, 2026 · Tested with GCC 13.3.0 · 8 min read
- Class, object, and struct
- The constructor and the initializer list
- Methods and const methods
- Access control: public and private
What this guide is
A class is a user-defined type that bundles data with the functions that operate on it. An object is one instance of that type, with its own copy of the data. The program uses GCC 13.3.0 with -std=c++17 -Wall -Wextra and exits with code 0.
The program
#include <iostream>
#include <string>
class Counter {
public:
Counter(std::string name) : name_(name), count_(0) {}
void increment() { count_++; }
int count() const { return count_; }
std::string name() const { return name_; }
private:
std::string name_;
int count_;
};
int main() {
Counter c("hits");
c.increment(); c.increment(); c.increment();
std::cout << c.name() << "=" << c.count() << "\n";
return 0;
}
The exact output:
hits=3
Three details in the program deserve a second look before the sections below explain them. First, the members are named name_ and count_, with a trailing underscore. That is a naming convention, not a language rule: it marks the names as members so they cannot be confused with the constructor parameter name or a local variable. Second, count() and name() end with const after the parameter list, while increment() does not. The const marks a method that promises not to change the object, and the compiler enforces the promise. Third, the constructor has no body that assigns anything. The work happens in the list after the colon, : name_(name), count_(0), which is the member initializer list, and that list is where members are set.
Class, object, and struct
A class defines a type. An object is a variable of that type. In the program, Counter is the class and c is the object: Counter c("hits"); creates one object, gives it the name hits, and sets its count to zero. The class is the blueprint, the object is the thing built from it, and two objects built from the same blueprint do not share state, as the second program in this guide shows.
struct defines the same kind of type, with one difference. The reference documentation states the rule in one sentence: a class defined with the keyword class has private access for its members and its base classes by default, and a class defined with the keyword struct has public access for its members and its base classes by default. That default is the only difference between the two keywords. A struct with public: written out behaves exactly like a class with public: written out.
The box run proves the difference with the smallest possible case. This program compiles:
struct S { int x; };
int main() { S s; s.x = 1; return 0; }
The same shape with class does not compile:
class C { int x; };
int main() { C c; c.x = 1; return 0; }
The compiler refuses it with this error:
error: 'int C::x' is private within this context
The member x is private because the class said nothing about access, and the default for class is private. The struct version works because its default is public. New code should write the access specifier out instead of relying on the default, so a reader never has to remember which keyword was used.
The constructor and the initializer list
The constructor runs when an object is created. Counter(std::string name) : name_(name), count_(0) {} takes the name the caller passes and uses it to initialize the member name_, while count_ starts at zero. The list after the colon is the member initializer list, and it runs before the constructor body. Members are initialized there, in the order they are declared in the class, not in the order they appear in the list.
The list matters because the body is too late for some members. A const member cannot be assigned to after it is initialized, and the constructor body runs after initialization. This program fails to compile:
class Fixed {
public:
Fixed(std::string name) { name_ = name; }
private:
const std::string name_;
};
The compiler refuses it with this error:
error: no match for 'operator=' (operand types are 'const std::string' {aka 'const std::__cxx11::basic_string<char>'} and 'std::string' {aka 'std::__cxx11::basic_string<char>'})
The assignment in the body tries to write to a const member, which is already fixed by the time the body runs. The fix is the initializer list, where the member is set at the moment it comes into being. The same rule applies to reference members and to members whose type has no default constructor: they must be initialized in the list, because the body can only assign to something that already exists.
The rule that follows is short. Put every member in the initializer list, even when the body could assign it. The list states the starting state of the object in one place, it works for const members and reference members, and it avoids the double work of default-constructing a member and then assigning over it.
Methods and const methods
A method is a function that belongs to the class and runs on one object. c.increment() calls the method on the object c, and the method changes c and no other object. Inside a method, the members are in scope without qualification: count_++ inside increment() means the count_ of the object the method was called on.
A method marked const promises not to change the object. int count() const { return count_; } reads the member and returns it, and the const is the compiler-checked record of that promise. The promise is enforced. This program fails to compile:
class Counter {
public:
Counter(std::string name) : name_(name), count_(0) {}
int count() const { count_++; return count_; }
private:
std::string name_;
int count_;
};
The compiler refuses it with this error:
error: increment of member 'Counter::count_' in read-only object
Inside a const method, the object is read-only, so any write to a member is an error at the line where it happens. The same rule governs the caller. A const object can only call const methods, because a call to a non-const method would hand a const object to code that is allowed to change it. The box run shows both sides: a const Counter calling count() compiles and prints 0, while the same object calling increment() fails with this error:
error: passing 'const Counter' as 'this' argument discards qualifiers [-fpermissive]
Access control: public and private
The class body is split by access specifiers. Members under public: can be used by any code. Members under private: can be used only by the class itself, by its methods and friends. In the program, the constructor and the three methods are public, because main must be able to create a Counter and call its methods. The data members name_ and count_ are private, because only the methods should read and change them.
The split is enforced by the compiler, not by convention. This program fails to compile:
int main() { Counter c("hits"); c.count_ = 5; return 0; }
The compiler refuses it with this error:
error: 'int Counter::count_' is private within this context
The error is the point of the split. Code outside the class cannot set the count directly, so it cannot put the object into a state the class never intended, such as a negative count for a counter that only ever increments. The only way to change the count is through increment(), and increment() only ever adds one. Private data plus public methods is how a class keeps its own rules: the data is hidden, the methods are the only door in, and the door only opens in the ways the class allows.
Two objects, each with its own state
The second program builds two counters from the same class and gives them different counts:
int main() {
Counter a("alpha");
Counter b("beta");
a.increment();
b.increment(); b.increment();
std::cout << a.name() << "=" << a.count() << " " << b.name() << "=" << b.count() << "\n";
return 0;
}
The exact output:
alpha=1 beta=2
Each object holds its own name_ and count_. Calling increment() on a changes only a, and calling it twice on b changes only b. The methods are shared code, the data is per object, and that split is what makes a class useful: one definition, as many independent objects as the program needs, each keeping its own state.
Trap 1: the missing semicolon
class Counter { int x; }
int main() { return 0; }
The compiler refuses it with this error:
error: expected ';' after class definition
The semicolon is required because a class definition can be followed by a list of objects, as in class Counter { ... } c;, which declares an object at the same time as the class. The semicolon marks the end of the definition, and without it the compiler reads the next line as a continuation of the declaration. The fix is one character, at the end of the closing brace.
Trap 2: defining a method outside the class
class Counter {
public:
void increment();
private:
int count_ = 0;
};
void increment() { count_++; }
The compiler refuses it with this error:
error: 'count_' was not declared in this scope
The definition void increment() is a free function, not a method: it has no object, so count_ means nothing inside it. The fix is the scope resolution operator, Counter::, which says the function belongs to the class:
void Counter::increment() { count_++; }
That version compiles, and a program calling it prints 1. The rule is the same for every out-of-class definition: the name must carry the class with it, or the function is a stranger to the class and cannot see its members.
Checklist
- Before writing a class, decide what data it owns and which methods are the only door to that data: members under
private:, methods underpublic:. - Before writing a constructor, put every member in the initializer list: a
constmember cannot be assigned in the body, and the list states the starting state in one place. - Before marking a method
const, check that it only reads: aconstmethod that writes to a member fails with a read-only error, and aconstobject can only callconstmethods. - Before choosing
structorclass, write the access specifier out: members are public by default in astructand private by default in aclass, and relying on the default makes the reader guess. - Before touching a member from outside the class, check whether it is private:
c.count_ = 5fails with a private-access error, and the fix is to go through a method. - Before assuming two objects share state, check the output:
alpha=1 beta=2shows each object keeps its ownname_andcount_. - Before finishing a class definition, check for the semicolon: a missing
;after the closing brace fails with an expected-semicolon error. - Before defining a method outside the class, check for the class name:
void increment()is a free function, and onlyvoid Counter::increment()can see the members.
Related guides on this site
- C++ Variables and Data Types: Declaration, Initialization, and Sizes — the previous guide in this foundation series, where a variable is declared, brace initialization rejects narrowing, and an uninitialized variable earns a warning.
- C++ Pointers and References: Addresses, Dereferencing, and nullptr — the previous guide in this foundation series, where a pointer can be re-pointed and a reference cannot, and assigning to a reference writes through it.
- C++20 Modules with CMake and Ninja — the first course guide, where modules replace headers.
- Migrating a Template Library from SFINAE to C++20 Concepts — the second course guide, where concepts replace
enable_if. - Modern C++ Guides: C++20 and C++23, Built and Run — the index of all the Modern C++ guides on this site.
Sources
- cppreference, Classes — a class is a user-defined type; class members, member functions, and the member access rules.
- cppreference, Constructors and member initializer lists — constructors initialize members, and the member initializer list is where initialization happens.
- cppreference, Access specifiers — a class defined with the keyword
classhas private access for its members by default, and a class defined withstructhas public access by default;privatemembers are accessible only to the class itself. - learncpp, Classes and class members — structure reference for how the topic is taught to beginners; all facts in this guide are grounded in the cppreference pages above and the box runs, not in this page.
Keep Exploring
Seven tips and seven puzzles so far, each one a short runnable example with the fix explained.
Paste an AddressSanitizer, UBSan, or ThreadSanitizer report and get the bug, the file and line, and the fix \u2014 in plain language.
C++20 and C++23 features, migration paths, and measured trade-offs.
The full C++ hub \u2014 language basics, the standard library, coroutines, and measured comparisons.
Paste a [Service] section and get a plain-language verdict on every sandboxing setting it finds.