Introduction & Syntax
Classes and Objects · Study material
Classes and objects in C++ are the building blocks of every object-oriented program. A class defines a new type – its data members and the member functions that operate on them – and an object is a variable of that type. Writing good classes means knowing the details: defining member functions inside and outside the class with ::, access specifiers, const member functions and mutable, default member initializers, the this pointer, static members, objects in arrays and as function parameters, where objects live and how long, nested and friend classes, aggregates with designated initializers, and C++20 defaulted comparisons. This page covers all of it with programs you can run, followed by 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.
On this page
- Defining a class; member functions inside and outside the class; header/source files
- Access specifiers, getters and setters, const member functions, mutable
- this, static data members and static member functions
- Arrays of objects, objects as parameters and return values, object lifetime
- Nested classes, friend classes, aggregates, designated initializers and operator<=>
Defining a class
A class definition lists data members and member functions inside braces and ends with a semicolon. Short functions are usually defined inside the class (they are implicitly inline); longer ones are declared inside and defined outside with the scope resolution operator: double Product::price_with_gst(double) const { … }. Data members can have default member initializers (int pin = 0;) used whenever a constructor does not set them.
#include <iostream>
#include <string>
class Product {
public:
// Member functions defined inside the class are implicitly inline
void set_price(double p) { if (p >= 0) price_ = p; }
double price() const { return price_; }
// Declared here, defined outside the class below
double price_with_gst(double rate) const;
void print() const;
std::string name = "Unnamed"; // default member initializer
private:
double price_ = 0.0;
};
// Outside definition: ClassName:: says which class the function belongs to
double Product::price_with_gst(double rate) const { return price_ * (1 + rate / 100); }
void Product::print() const { std::cout << name << ": " << price_ << " (+GST " << price_with_gst(18) << ")\n"; }
int main() {
Product p;
p.name = "Notebook";
p.set_price(50);
p.set_price(-10); // rejected by the setter
p.print();
Product q; // uses the default member initializers
q.print();
return 0;
}
Notebook: 50 (+GST 59) Unnamed: 0 (+GST 0)
Splitting a class into header and source files
In real projects the class definition goes in a header (.h/.hpp) that other files include, and the member function definitions go in a source file (.cpp) that is compiled once. Include guards or #pragma once stop the header from being included twice.
// ---- student.h ----
#pragma once
#include <string>
class Student {
public:
Student(std::string name, int marks);
char grade() const;
const std::string& name() const { return name_; } // short: defined inline
private:
std::string name_;
int marks_;
};
// ---- student.cpp ----
#include "student.h"
Student::Student(std::string name, int marks) : name_(std::move(name)), marks_(marks) {}
char Student::grade() const {
return marks_ >= 85 ? 'A' : marks_ >= 70 ? 'B' : marks_ >= 50 ? 'C' : 'F';
}
// ---- main.cpp ----
#include "student.h"
// g++ -std=c++20 main.cpp student.cpp -o app
Access specifiers, getters and setters
public members are the class's interface, private members its implementation details, protected members are also open to derived classes. Members of a class are private until a specifier says otherwise; members of a struct are public. Getters return information; setters change it after validating – which is how a class keeps its data consistent.
const member functions and mutable
Putting const after a member function's parameter list promises it does not modify the object. Only const member functions can be called on const objects and through const references – which is how objects are usually passed to functions. A data member declared mutable may still change inside const functions; it is meant for caches, counters and mutexes that are not part of the object's logical value.
#include <iostream>
#include <string>
class Document {
std::string text_;
mutable int reads_ = 0; // may change even inside const functions
public:
explicit Document(std::string t) : text_(std::move(t)) {}
const std::string& text() const { ++reads_; return text_; } // const: does not change the document
void append(const std::string& more) { text_ += more; } // non-const: changes it
int reads() const { return reads_; }
};
void show(const Document& d) { // const reference: only const members can be called
std::cout << d.text() << '\n';
// d.append("!"); error: append is not const
}
int main() {
Document doc("Draft");
doc.append(" v2");
show(doc);
show(doc);
std::cout << "read " << doc.reads() << " times\n";
return 0;
}
Draft v2 Draft v2 read 2 times
The this pointer
Every non-static member function receives a hidden pointer, this, to the object it was called on. Use this->x when a parameter has the same name as a member, return *this by reference to allow method chaining, and compare this with an address to detect self-assignment.
#include <iostream>
class Point {
int x, y;
public:
Point(int x, int y) { this->x = x; this->y = y; } // this-> separates members from parameters
Point& move_by(int dx, int dy) { x += dx; y += dy; return *this; }
bool same_object(const Point& other) const { return this == &other; }
void print() const { std::cout << '(' << x << ", " << y << ")\n"; }
};
int main() {
Point p(1, 2);
p.move_by(3, 0).move_by(0, 4).print();
Point q = p;
std::cout << p.same_object(p) << p.same_object(q) << '\n';
return 0;
}
(4, 6) 10
Static members
A static data member exists once per class, shared by all objects. Since C++17 it can be defined inside the class with static inline; constants use static constexpr. A static member function has no this, can use only static members, and is called as ClassName::function().
#include <iostream>
#include <string>
class Ticket {
static inline int next_id_ = 1001; // C++17 inline static: defined right here
static constexpr int max_per_user = 4; // compile-time constant member
int id_;
std::string holder_;
public:
explicit Ticket(std::string h) : id_(next_id_++), holder_(std::move(h)) {}
int id() const { return id_; }
static int issued() { return next_id_ - 1001; } // no this – uses only static data
static int limit() { return max_per_user; }
};
int main() {
Ticket a("Asha"), b("Ravi"), c("Meera");
std::cout << a.id() << ' ' << c.id() << ' ' << Ticket::issued() << ' ' << Ticket::limit() << '\n';
return 0;
}
1001 1003 3 4
Objects in arrays, as parameters and as return values
Objects can be stored in arrays and containers, passed to functions and returned from them like any other value. Pass by const& to read without copying, by & to modify, and return by value – the compiler elides or moves the copy.
#include <iostream>
#include <string>
#include <vector>
struct Item {
std::string name;
int qty;
double price;
double total() const { return qty * price; }
};
Item cheaper(const Item& a, const Item& b) { return a.price <= b.price ? a : b; } // returns a copy
void restock(Item& it, int n) { it.qty += n; } // modifies the caller's object
int main() {
Item shelf[3] = {{"pen", 10, 12.5}, {"pencil", 25, 6}, {"eraser", 8, 5}}; // array of objects
restock(shelf[2], 12);
double value = 0;
for (const Item& it : shelf) value += it.total();
std::vector<Item> cart{shelf[0], shelf[1]};
std::cout << shelf[2].qty << ' ' << value << ' ' << cheaper(cart[0], cart[1]).name << '\n';
return 0;
}
20 375 pencil
Where objects live: storage duration
| Kind | Created | Destroyed |
|---|---|---|
| Automatic (local) | when its definition is reached | at the end of its block |
| Static (global, namespace, static member) | before main starts | after main returns |
| Static local | the first time control reaches it | after main returns |
Dynamic (new, smart pointers) | when allocated | when deleted / when its owner is destroyed |
#include <iostream>
#include <memory>
#include <string>
struct Tracer {
std::string tag;
explicit Tracer(std::string t) : tag(std::move(t)) { std::cout << "+" << tag << ' '; }
~Tracer() { std::cout << "-" << tag << ' '; }
};
Tracer global_obj("global"); // static storage: before main, destroyed after main
void counter() {
static Tracer once("static-local"); // created the first time control reaches it
}
int main() {
std::cout << "| main ";
Tracer stack_obj("stack"); // automatic: destroyed at the end of main's block
counter();
counter();
{
auto heap_obj = std::make_unique<Tracer>("heap"); // dynamic, owned by a smart pointer
}
std::cout << "| end ";
return 0;
}
+global | main +stack +static-local +heap -heap | end -stack -static-local -global
Aggregates and designated initializers
A class with only public data members, no user-declared constructors and no virtual functions is an aggregate; it can be initialized with braces in member order. C++20 adds designated initializers – {.city = "Nagpur", .pin = 440001} – which name the members (in declaration order) and let the others keep their defaults.
#include <iostream>
#include <string>
struct Address { // aggregate: public data, no user constructors
std::string city;
std::string state = "Maharashtra";
int pin = 0;
};
int main() {
Address a{"Pune", "Maharashtra", 411001}; // positional
Address b{.city = "Nagpur", .pin = 440001}; // C++20 designated initializers (state keeps its default)
Address c{"Nashik"}; // remaining members: defaults
std::cout << a.city << ' ' << a.pin << " | " << b.city << ' ' << b.state << ' ' << b.pin
<< " | " << c.city << ' ' << c.pin << '\n';
return 0;
}
Pune 411001 | Nagpur Maharashtra 440001 | Nashik 0
Comparing objects: == and the spaceship operator
Objects cannot be compared with == or < unless the class defines those operators. C++20 lets you write auto operator<=>(const T&) const = default; to get all six comparisons, comparing members in declaration order – handy for sorting and for using objects as map keys.
#include <algorithm>
#include <compare>
#include <iostream>
#include <string>
#include <vector>
struct Version {
int major, minor, patch;
auto operator<=>(const Version&) const = default; // C++20: ==, !=, <, <=, >, >= member by member
};
int main() {
Version a{1, 4, 2}, b{1, 10, 0}, c{1, 4, 2};
std::cout << (a < b) << (a == c) << (b > c) << (a != b) << '\n';
std::vector<Version> v{{2, 0, 0}, {1, 9, 9}, {1, 10, 0}};
std::sort(v.begin(), v.end());
for (const auto& x : v) std::cout << x.major << '.' << x.minor << '.' << x.patch << ' ';
std::cout << '\n';
return 0;
}
1111 1.9.9 1.10.0 2.0.0
Nested classes and friend classes
A class defined inside another (Playlist::Song) groups helper types with the class that uses them; it is a member and follows the access specifiers. A friend class declaration grants another class access to private members – use it for tightly coupled helpers such as printers, iterators or builders.
#include <iostream>
#include <string>
#include <vector>
class Playlist {
public:
struct Song { // nested class: Playlist::Song
std::string title;
int seconds;
};
void add(Song s) { songs_.push_back(std::move(s)); }
friend class PlaylistPrinter; // PlaylistPrinter may use private members
private:
std::vector<Song> songs_;
};
class PlaylistPrinter {
public:
static void print(const Playlist& p) {
int total = 0;
for (const auto& s : p.songs_) { // allowed: friend class
std::cout << s.title << ' ' << s.seconds / 60 << ':' << (s.seconds % 60 < 10 ? "0" : "") << s.seconds % 60 << '\n';
total += s.seconds;
}
std::cout << "total " << total / 60 << " min\n";
}
};
int main() {
Playlist p;
p.add({"Kesariya", 268});
p.add(Playlist::Song{"Ilahi", 205});
PlaylistPrinter::print(p);
return 0;
}
Kesariya 4:28 Ilahi 3:25 total 7 min
The size of an object
sizeof an object is the sum of its non-static data members plus any padding the compiler adds for alignment (plus a hidden vtable pointer for classes with virtual functions). Member functions and static members take no space in each object. An empty class still has size 1, so that distinct objects have distinct addresses.
Common mistakes
- Forgetting ClassName:: when defining a member function outside the class – you define a free function instead.
- Missing const on getters – they cannot be called on const objects or const references.
- Non-const static members initialized in the class without
inline. - Returning a reference to a member of a temporary object.
- Public data members in classes that need rules – use private data and setters.
- Comparing objects with == without defining an operator.
Key points to remember
- A class ends with }; and its members are private by default.
- Define members outside with ReturnType ClassName::name(…).
- Mark non-modifying member functions const; mutable members may still change.
- this points to the current object; return *this to chain calls.
- Static members belong to the class; static functions have no this.
- = default on operator<=> gives all comparisons (C++20).
Frequently asked questions
Should member functions be defined inside or outside the class?
Define one-liners inside the class (they become inline). Define longer functions outside, in a .cpp file, so the header stays readable and changes recompile less code.
What is the difference between a class and a struct?
Only default access: private for class, public for struct. Use struct for simple aggregates of public data, class for types with invariants and private data.
Do member functions increase the size of each object?
No – there is one copy of each function for the whole program. Only non-static data members (plus padding and a possible vtable pointer) occupy space in an object.
Where can I learn more?
Read C++ Classes and Objects and Object-Oriented Programming in C++, then practise with the exercises below.