Language[lang]
C++ class: how to define one and create objects
- Section
- Language [lang]
- Standard
- C++17
- Compilers
- MSVC 19.44, Clang 19.1 (MSVC STL), GCC 16.2, Clang 23.1 (libc++)
- Published
- Length
- 7 min read
In this answer7 clauses
- 1How do you define a class in C++?
- 2How do you create an object of a class in C++?
- 3What is a constructor in C++?
- 4What does const after a member function mean?
- 5How do you split a class into a header and a source file?
- 6Class or struct: which should you use?
- 7What are the common mistakes with C++ classes?
Abstract
A C++ class is a type that bundles data with the functions that work on it. Its members are private by default: put the data under private: and the functions other code may call under public:, give every data member a default value or set it in a constructor, and mark the functions that only read const. An object is one instance of the class, such as Account savings;, and each object has its own copy of the data.

A C++ class is a type you define that bundles data with the functions that work on it: class Account { ... };. Its members are private unless you list them under public:, so the class decides what outside code may touch. An object is one instance of that type, declared like any variable: Account savings;.
A C++ class example as a whole program, with a main that uses it:
#include <iostream>
class Account {
public:
void deposit(int amount) {
balance_ += amount;
}
bool withdraw(int amount) {
if (amount > balance_) {
return false; // refused: never below zero
}
balance_ -= amount;
return true;
}
int balance() const {
return balance_;
}
private:
int balance_ = 0;
};
int main() {
Account savings;
savings.deposit(100);
savings.withdraw(30);
if (!savings.withdraw(500)) {
std::cout << "refused\n"; // prints refused
}
std::cout << savings.balance() << '\n'; // prints 70
}— end example]
It printed:
refused
70— end example]
The samples are C++17, built with MSVC 19.44, Clang 19.1 (MSVC STL), GCC 16.2 and Clang 23.1 (libc++), and all four printed the same. Nothing on this page needs a newer standard; Since When lists what each one added.
How do you define a class in C++?
Write the keyword class, a name, the members between braces, and a semicolon after the closing brace. Everything declared inside the braces of a class definition is a member: balance_ is a data member, and deposit, withdraw and balance are member functions. The data goes under private:, the functions outside code may call under public:. A third label, protected:, matters only once one class inherits from another (inheritance in C++). The trailing underscore keeps the data member’s name apart from the function balance().
Private data is the point of a class. Only Account’s own functions and its friends can change balance_, so a rule about the balance is kept inside the class, in one place, and no code outside can set it directly. withdraw enforces “never below zero” here; a finished class would make deposit refuse a negative amount too. The C++ Core Guidelines ask for the same in C.9, minimize exposure of members.

Reach for balance_ from outside, and the program does not compile:
int main() {
Account savings;
savings.balance_ = 1000000; // error: balance_ is private
}— end example]
Clang said:
error: 'balance_' is a private member of 'Account'— end example]
GCC and MSVC refuse it too.
How do you create an object of a class in C++?
Declare a variable whose type is the class, then call its member functions with a dot: savings.deposit(100). Each object has its own copy of the data, so two accounts keep two balances:
int main() {
Account savings;
Account checking;
savings.deposit(100);
checking.deposit(25);
std::cout << savings.balance() << '\n'; // prints 100
std::cout << checking.balance() << '\n'; // prints 25
}— end example]
It printed 100, then 25. Account is the class; savings and checking are two objects of it, also called instances.
What is a constructor in C++?
A constructor is a member function that runs when an object is created, to give its data starting values; it has the class’s name and no return type. Account has none and needs none: int balance_ = 0; gives the member a default value, and with no constructor written, the compiler declares a default one for you.
To open an account with an owner and a starting balance, write a constructor that takes them. This is what changes, with #include <string> at the top:
class Account {
public:
Account(const std::string& owner, int opening)
: owner_(owner), balance_(opening) {}
const std::string& owner() const {
return owner_;
}
// ...
private:
std::string owner_;
int balance_ = 0;
};
int main() {
Account savings{"Ana", 100}; // the constructor runs here
std::cout << savings.owner() << '\n'; // prints Ana
std::cout << savings.balance() << '\n'; // prints 100
}— end example]
It printed Ana and 100. The part after the colon, the member initializer list, sets each member from the arguments, and for balance_ it wins over the = 0. Declaring any constructor stops the compiler from declaring the default one (default constructors), so this Account can no longer be created as Account savings;. C++ constructors covers the other kinds, copy and move, and explicit. The rest of the page goes back to the first Account, which has no constructor.
What does const after a member function mean?
const after the parameter list, as in int balance() const, promises that the function does not change the object it is called on. A function that takes a const Account&, a reference that may only read the object, can call only such const member functions:
void print(const Account& account) {
std::cout << account.balance() << '\n'; // balance() is const
}
int main() {
Account savings;
savings.deposit(100);
print(savings); // prints 100
}— end example]
It printed 100. Call deposit from the same function, and none of the four compilers accepts it:
void print(const Account& account) {
account.deposit(1); // error: deposit() is not const
std::cout << account.balance() << '\n';
}— end example]
Clang put it most plainly:
error: 'this' argument to member function 'deposit' has type 'const Account', but function is not marked const— end example]
The 'this' argument is the object the function is called on, here a const Account. Declare every member function that only reads as const; const in C++ covers const on variables, pointers and references too.
How do you split a class into a header and a source file?
Put the class, with its member functions declared but not defined, in a header such as account.h, and the bodies in account.cpp, each named with the class in front: void Account::.
// account.h: the class, with its member functions declared
class Account {
public:
void deposit(int amount);
bool withdraw(int amount);
int balance() const;
private:
int balance_ = 0;
};
// ...
// account.cpp: the bodies, each named with Account:: in front
void Account::deposit(int amount) {
balance_ += amount;
}
// ...
int Account::balance() const { // const here as well
return balance_;
}— end example]
Account:: says which class a function belongs to, and the const is written again on the definition. Built as one file, with the first program’s main after the definitions, it printed refused and 70 again. As separate files, account.h starts with #pragma once (or an include guard), and account.cpp and the file with main each start with #include "account.h"; C++ header files shows both and how to build the files together.
Class or struct: which should you use?
Use class when the type has a rule to protect, like Account’s balance, and struct for plain data whose members can each take any value, as C.2 of the C++ Core Guidelines advises. The two keywords make the same kind of type and differ only in the access you get when you write no label, for members and for base classes (class declaration):
| By default | class |
struct |
|---|---|---|
| Members | private | public |
| Base classes | private | public |
Struct in C++ shows the struct side: braces, default values and passing one to a function.
What are the common mistakes with C++ classes?
A missing semicolon after the closing brace is the one whose message can point at the wrong line:
private:
int balance_ = 0;
} // error: the semicolon after the brace is missing
int main() {— end example]
GCC and Clang point at the brace and suggest the ;; GCC says error: expected ';' after class definition. MSVC reads Account as the return type of what follows and reports the next line of code, int main(), with error C2628: 'Account' followed by 'int' is illegal (did you forget a ';'?), so on MSVC the error shows up below the mistake.
The other three:
- No
public:at all. Every member is then private, sosavings.deposit(100)frommainfails asbalance_did. Clang says'deposit' is a private member of 'Account'and notes that it was “implicitly declared private here”. - A data member with no value. Without
= 0and without a constructor that sets it,Account savings;inside a function leavesbalance_indeterminate, never set to anything. Give every data member a default value, or set it in a constructor. - A reading function left without
const. Writeint balance()without it, andprintcan no longer call it through itsconst Account&: all four refuse it as they refuseddeposit.
Once a class like Account works, inheritance in C++ is the next step: one class built on another. More answers about the core language are in Language.
Questions
What is the difference between a class and an object in C++?
A class is a type: it says what data each object holds and which functions can be called on it. An object is one instance of that type, with its own copy of the data. Account savings; and Account checking; are two objects of one Account class, and a deposit into one leaves the other’s balance unchanged.
Are class members private by default in C++?
Yes. In a class declared with the keyword class, every member is private until an access label such as public: says otherwise, so only the class’s own member functions, and functions it declares as friends, can use it. In a struct, members are public by default.
What is the difference between a class and a struct in C++?
Only the defaults. A class’s members and base classes are private unless you say otherwise; a struct’s are public. Both can have constructors, member functions and private members, so the keyword tells the reader what to expect: class for a type that guards its data, struct for plain data.
What is this in C++?
Inside a member function, this is a pointer to the object the function was called on: in savings.deposit(100), this points to savings. In a const member function such as balance() const, this is a pointer to a const Account, so the function cannot change the object through it.
Can a class contain an object of its own type?
No. class Node { Node next; }; does not compile, because Node is not complete until its closing brace; GCC says field ‘next’ has incomplete type ‘Node’. A pointer to one is fine: Node* next = nullptr; in its place drew no error from GCC, Clang or MSVC.
How do you make a vector of objects in C++?
Write std::vector<Account> accounts;, as for any other element type, and add an object with accounts.push_back(savings);. The vector keeps a copy with its own balance: after savings.deposit(50), accounts[0].balance() still printed 100 and savings.balance() 150. Each element is a whole Account object, and a dot after one calls its member functions.
Sources
- Class declarationcppreference.com
- Access specifierscppreference.com
- Non-static member functionscppreference.com
- The this pointercppreference.com
- Default constructorscppreference.com
- [class.access.general] Member access controlC++ standard working draft
- C.2: Use class if the class has an invariant; use struct if the data members can vary independentlyC++ Core Guidelines
- C.9: Minimize exposure of membersC++ Core Guidelines