C++ Classes and Objects: Complete Guide — Constructors, Destructors, Encapsulation & DSA (2025)
âš¡ Quick Answer: Classes and Objects in C++
- class — blueprint combining data + behavior; default access is
private - object — runtime instance of a class, has its own copy of member variables
- Access specifiers —
public,private,protectedcontrol visibility - Constructor — called on creation; types: default, parameterized, copy, move
- Destructor —
~ClassName()called on destruction; release resources here - Encapsulation — private data + public interface = protected invariants
- Rule of Three/Five — if you define a destructor, also define copy/move ops
Classes and objects are the heart of C++ OOP — they are the building blocks for every data structure you'll implement: linked lists, stacks, queues, trees, and graphs. This guide covers everything from the absolute basics to the Rule of Three/Five, with complete annotated examples, a visual class anatomy diagram, and five DSA implementations.
Class Basics
Declaration & syntax
Access Specifiers
public / private / protected
Constructors
All 4 types explained
Destructors
Cleanup & memory
Encapsulation
Getters, setters, this
Rule of Three/Five
Deep copy & move
class vs struct
When to use which
DSA Examples
5 complete classes
Class Declaration, Anatomy & First Object
A class is a user-defined type that bundles data (member variables) and behavior (member functions/methods). By itself a class definition allocates no memory — only when you create an object does memory get allocated.
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int id;
public:
// Parameterized constructor with initializer list
Student(string n, int i) : name(n), id(i) {
cout << "Constructor: " << name << endl;
}
// Destructor
~Student() {
cout << "Destructor: " << name << endl;
}
// Const method — cannot modify *this
void display() const {
cout << "Name: " << name << ", ID: " << id << endl;
}
void setName(string n) { name = n; }
string getName() const { return name; }
};
int main() {
// Stack object — destroyed when scope ends
Student s1("Alice", 101);
s1.display(); // dot operator
// Heap object — destroyed when we delete
Student* s2 = new Student("Bob", 102);
s2->display(); // arrow operator
s2->setName("Robert");
s2->display();
delete s2; // destructor called here
// s1 destructor called here (scope end)
return 0;
}
Constructor: Alice
Constructor: Bob
Name: Alice, ID: 101
Name: Bob, ID: 102
Name: Robert, ID: 102
Destructor: Robert
Destructor: AliceAccess Specifiers: public, private, protected
public
Accessible from anywhere — inside the class, from objects, from derived classes.
Use for: methods, constructors, the public interfaceprivate
Accessible only within the class's own methods. Default for class.
protected
Accessible within the class AND derived (child) classes. Not from outside.
Use for: members derived classes need to extendprivate. Expose what callers
need through public methods. This lets you change the internal representation
without breaking code that uses your class — the definition of a stable API.
Constructors — All 4 Types With Examples
A constructor is a special member function called automatically when an object is created. It has the same name as the class, no return type, and can be overloaded.
MyClass obj;. Compiler auto-generates one if you define no constructors. MyClass() : x(0) {}MyClass(int v) : x(v) {}. Called by MyClass obj(5); or MyClass obj{5};MyClass(const MyClass& o) : x(o.x) {}. Called by MyClass b = a;MyClass(MyClass&& o) : x(o.x) { o.x=nullptr; }. Enables efficient vector resizing.#include <iostream>
using namespace std;
class Point {
public:
double x, y;
// 1. Default constructor
Point() : x(0), y(0) {
cout << "Default ctor: (0,0)\n";
}
// 2. Parameterized constructor
Point(double px, double py) : x(px), y(py) {
cout << "Param ctor: (" << x << "," << y << ")\n";
}
// 3. Copy constructor
Point(const Point& o) : x(o.x), y(o.y) {
cout << "Copy ctor: (" << x << "," << y << ")\n";
}
void print() const { cout << "("<<x<<","<<y<<")\n"; }
};
int main() {
Point p1; // default ctor
Point p2(3.0,4.0); // parameterized
Point p3 = p2; // copy ctor
Point p4(p2); // also copy ctor
return 0;
}
Default ctor: (0,0)
Param ctor: (3,4)
Copy ctor: (3,4)
Copy ctor: (3,4)class Circle {
const double PI; // const member — MUST use initializer list
double& ref; // reference member — MUST use initializer list
double r;
public:
// Initializer list runs BEFORE the constructor body
// Order matches declaration order, not list order!
Circle(double& external, double radius)
: PI(3.14159), // const — can only be init, not assigned
ref(external), // reference — can only be init, not assigned
r(radius) // preferred: direct init, not default+assign
{ }
double area() const { return PI * r * r; }
};
// WITHOUT initializer list these would be compile errors:
// Circle(...) { PI = 3.14; } ↠error: assignment to const
// Circle(...) { ref = x; } ↠error: reference must be initialized
const and reference members,
initializer lists are mandatory. For all other members, they are preferred:
a member initialized in the list is constructed directly from the value; one assigned in the
body is first default-constructed, then assigned — two operations instead of one.
Destructors and Resource Management
The destructor (~ClassName()) runs automatically when an object is destroyed —
when a stack object leaves scope, or when delete is called on a heap object.
Its job: release any resource the object owns (heap memory, file handles, network connections, locks).
#include <iostream>
using namespace std;
class DynamicArray {
int* data;
int size;
public:
DynamicArray(int n) : size(n), data(new int[n]()) {
// new int[n]() zero-initializes the array
cout << "Allocated " << n << " ints\n";
}
~DynamicArray() {
delete[] data; // [] required for arrays — not delete data
cout << "Freed array of size " << size << "\n";
}
int& operator[](int i) { return data[i]; }
int getSize() const { return size; }
};
int main() {
{ // inner scope
DynamicArray arr(5);
arr[0] = 10; arr[1] = 20;
cout << arr[0] << " " << arr[1] << endl;
} // ↠destructor called here automatically
cout << "Back in outer scope\n";
return 0;
}
Allocated 5 ints
10 20
Freed array of size 5
Back in outer scopedelete[] for arrays allocated with new[].
Using delete (without []) on an array is undefined behavior — typically
only the first element's destructor runs and the rest of the memory is leaked. Pair
new T[n] with delete[] and new T with delete.
Better yet: use std::vector<T> which handles this automatically.
Encapsulation, Getters/Setters, const Methods & this
#include <iostream>
#include <stdexcept>
using namespace std;
class BankAccount {
private:
double balance;
string owner;
public:
BankAccount(string owner, double initial)
: owner(owner), balance(initial) {}
// const getter — returns a copy; const objects can call this
double getBalance() const { return balance; }
string getOwner() const { return owner; }
// Validated setter — encapsulation enforces invariant
void deposit(double amount) {
if (amount <= 0) throw invalid_argument("Deposit must be positive");
balance += amount;
}
void withdraw(double amount) {
if (amount > balance) throw runtime_error("Insufficient funds");
balance -= amount;
}
// 'this' used to disambiguate and for method chaining
BankAccount& setOwner(string owner) {
this->owner = owner; // 'this->owner' = member, 'owner' = param
return *this; // enables chaining: acc.setOwner("X").deposit(100)
}
void display() const {
cout << owner << ": $" << balance << endl;
}
};
int main() {
BankAccount acc("Alice", 1000.0);
acc.deposit(500.0);
acc.withdraw(200.0);
acc.display();
// Method chaining using *this
acc.setOwner("Alice Smith").deposit(100.0);
acc.display();
try {
acc.withdraw(99999.0); // throws — balance protected
} catch(const exception& e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}
Alice: $1300
Alice Smith: $1400
Error: Insufficient fundsRule of Three & Rule of Five
When a class manually manages a resource (heap memory, file handle, mutex), the compiler- generated copy/move operations do the wrong thing. The Rule of Three (C++03) and Rule of Five (C++11) tell you when to define your own.
| Special function | Called when | Default behavior | Must define when… |
|---|---|---|---|
| Destructor | Object destroyed | Does nothing | Class owns heap resources |
| Copy constructor | MyClass b = a; | Shallow copy | Shallow copy causes double-free |
| Copy assignment | b = a; (after both exist) | Shallow copy | Same as above |
| Move constructor (C++11) | MyClass b = move(a); | Shallow copy | Performance: transfer, not copy |
| Move assignment (C++11) | b = move(a); | Shallow copy | Same as move constructor |
#include <iostream>
#include <cstring> // memcpy
using namespace std;
class Buffer {
int* data;
int size;
public:
Buffer(int n) : size(n), data(new int[n]()) {}
// 1. Destructor
~Buffer() { delete[] data; }
// 2. Copy constructor — DEEP copy
Buffer(const Buffer& o) : size(o.size), data(new int[o.size]) {
memcpy(data, o.data, size * sizeof(int));
}
// 3. Copy assignment — deep copy + self-assignment guard
Buffer& operator=(const Buffer& o) {
if (this == &o) return *this; // self-assignment guard
delete[] data;
size = o.size;
data = new int[size];
memcpy(data, o.data, size * sizeof(int));
return *this;
}
int& operator[](int i) { return data[i]; }
int getSize() const { return size; }
};
int main() {
Buffer a(3); a[0]=1; a[1]=2; a[2]=3;
Buffer b = a; // copy constructor — DEEP copy
b[0] = 99; // modifying b should NOT affect a
cout << a[0] << endl; // 1 — independent copy ✓
cout << b[0] << endl; // 99
return 0;
}
1
99std::vector, std::unique_ptr, or std::shared_ptr
as member types. These handle deep copying and cleanup automatically — your class can use
the compiler-generated defaults and get correct behavior for free.
class vs struct — When to Use Which
| Feature | class | struct |
|---|---|---|
| Default access | private | public |
| Default inheritance | private | public |
| Supports methods | ✓ Yes | ✓ Yes |
| Supports constructors | ✓ Yes | ✓ Yes |
| Supports inheritance | ✓ Yes | ✓ Yes |
| Convention | Complex objects with encapsulation | Plain data grouping, competitive programming |
// struct: plain data record, no invariants to enforce
struct Point {
double x, y; // public by default — fine for plain data
};
// struct in competitive programming — custom comparator for Kruskal's
struct Edge {
int u, v, w;
bool operator<(const Edge& e) const { return w < e.w; }
};
// class: complex object with invariants — private data, public interface
class BankAccount {
private:
double balance; // invariant: balance >= 0 enforced by methods
public:
void deposit(double a); // validates before modifying
void withdraw(double a); // validates before modifying
};
DSA Applications: 5 Complete Class-Based Data Structures
1. Linked List
#include <iostream>
using namespace std;
class LinkedList {
private:
struct Node { // nested private struct
int data;
Node* next;
Node(int v) : data(v), next(nullptr) {}
};
Node* head;
int sz;
public:
LinkedList() : head(nullptr), sz(0) {}
~LinkedList() { // destructor frees all nodes
while (head) {
Node* t = head;
head = head->next;
delete t;
}
}
void push_front(int v) {
Node* n = new Node(v);
n->next = head;
head = n; sz++;
}
void push_back(int v) {
Node* n = new Node(v);
if (!head) { head = n; sz++; return; }
Node* cur = head;
while (cur->next) cur = cur->next;
cur->next = n; sz++;
}
void display() const {
for (Node* c = head; c; c = c->next)
cout << c->data << " → ";
cout << "null\n";
}
int size() const { return sz; }
};
int main() {
LinkedList lst;
lst.push_back(1); lst.push_back(2); lst.push_back(3);
lst.push_front(0);
lst.display();
cout << "Size: " << lst.size() << endl;
return 0; // destructor frees all nodes
}
0 → 1 → 2 → 3 → null
Size: 42. Stack (array-based)
#include <iostream>
#include <stdexcept>
using namespace std;
template<typename T, int MAX = 100>
class Stack {
T arr[MAX];
int top;
public:
Stack() : top(-1) {}
void push(const T& v) {
if (top == MAX-1) throw overflow_error("Stack full");
arr[++top] = v;
}
T pop() {
if (isEmpty()) throw underflow_error("Stack empty");
return arr[top--];
}
const T& peek() const {
if (isEmpty()) throw underflow_error("Stack empty");
return arr[top];
}
bool isEmpty() const { return top == -1; }
int size() const { return top + 1; }
};
int main() {
Stack<int> s;
s.push(10); s.push(20); s.push(30);
cout << "Top: " << s.peek() << endl;
while (!s.isEmpty()) cout << s.pop() << " ";
cout << endl;
return 0;
}
Top: 30
30 20 10 3. BST Node — struct for competitive programming
#include <iostream>
using namespace std;
struct BST {
int val;
BST* left = nullptr;
BST* right = nullptr;
BST(int v) : val(v) {}
static BST* insert(BST* root, int v) {
if (!root) return new BST(v);
if (v < root->val) root->left = insert(root->left, v);
else root->right = insert(root->right, v);
return root;
}
static void inorder(BST* root) {
if (!root) return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
};
int main() {
BST* root = nullptr;
for (int x : {5,3,7,1,4,6,8}) root = BST::insert(root, x);
cout << "Inorder: ";
BST::inorder(root);
cout << endl;
return 0;
}
Inorder: 1 3 4 5 6 7 8 Best Practices & Common Mistakes
✅ Private data, public interface
Never expose data members directly. Use methods that validate before modifying — that's the point of encapsulation.
✅ Use initializer lists
Always initialize members in the constructor's initializer list. Required for const and reference members; preferred everywhere else.
✅ Mark read-only methods const
int getX() const — lets const objects and const references call the method. Without const, passing your object as const ref breaks.
✅ Follow Rule of Three/Five
If your class manages heap memory (raw pointer + new), define the destructor, copy constructor, and copy assignment. Better: use std::vector/unique_ptr instead.
✅ Give base classes virtual destructors
If your class is used polymorphically (Base* p = new Derived()), the base destructor MUST be virtual — otherwise only the base destructor runs on delete.
✅ Use smart pointers
unique_ptr and shared_ptr handle destruction automatically — eliminating the need to manually implement the Rule of Three in most cases.
⌠Uninitialized members
Local variables of built-in types (int, double) in an uninitialized object contain garbage. Initialize ALL members in constructors.
⌠delete without delete[]
For int* arr = new int[n], always use delete[] arr. Using plain delete arr is undefined behavior.
Frequently Asked Questions
class defaults to private; struct defaults to public. Both support all OOP features: constructors, destructors, methods, inheritance, and templates. Convention: use struct for plain data aggregation with no invariants to protect; use class when you need encapsulation (private data + validated public interface).const members — cannot be assigned after construction. (2) Reference members — same reason. (3) Member objects without a default constructor. (4) All other members — preferred because it initializes directly rather than default-constructing then assigning (two operations vs one). The initializer list executes before the constructor body in declaration order.this is a pointer to the current object available inside every non-static member function. It's used to: (1) Disambiguate when a parameter has the same name as a member: this->name = name;. (2) Return the current object for method chaining: return *this;. (3) Pass the current object to another function. In const member functions, this is a pointer to const — you cannot modify members through it.virtual ~Base() = default; to any class intended to be used as a base class. Rule: if any method in your class is virtual, the destructor should be virtual too.MyClass obj;) when: the object's lifetime should be tied to the current scope, and the object is of reasonable size. Use heap allocation (new MyClass()) when: the object must outlive the current scope, the object is very large, or you need polymorphism via a base pointer. In modern C++, prefer std::make_unique<MyClass>() over raw new — it prevents leaks even when exceptions are thrown.Build DSA data structures with C++ classes
Structured lessons, 200+ exercises, certificate. Join 50,000+ students on CoodeVerse.
Related C++ Topics on CoodeVerse
Frequently asked questions
What is a class in C++?
A class in C++ is a user-defined type that combines data (member variables) and behavior (member functions) into a single unit. It acts as a blueprint for creating objects. Example: class Car { private: int speed; public: void accelerate(); }; A class on its own occupies no memory — only when you create an object does memory get allocated. Classes are the foundation of OOP in C++ and are used to implement data structures like linked lists, stacks, trees, and graphs.
What is an object in C++?
An object is a specific instance of a class — the actual runtime entity that occupies memory. If Car is a class, Car myCar; creates an object myCar with its own copy of the class's member variables. You access members with the dot operator: myCar.accelerate(). For objects on the heap (new): Car* p = new Car(); p->accelerate(); delete p;
What are access specifiers in C++ classes?
Access specifiers control which code can access class members. Three specifiers: (1) public — accessible from anywhere. (2) private — accessible only within the class's own methods (default for class keyword). (3) protected — accessible within the class and its derived (child) classes, not from outside. Best practice: make data members private, expose them only through public getter/setter methods — this is encapsulation.
What are constructors in C++ and how many types are there?
A constructor is a special member function with the same name as the class, called automatically when an object is created. It has no return type. Types: (1) Default constructor: takes no parameters — created automatically if you define none. (2) Parameterized constructor: takes arguments to initialize members. (3) Copy constructor: takes a const reference to the same class, used when copying objects. (4) Move constructor (C++11): takes an rvalue reference, transfers resources instead of copying. All constructors can use initializer lists: Student(string n): name(n) {} — preferred over assignment in the body.
What is a destructor in C++ and when is it called?
A destructor is a special member function named ~ClassName() with no parameters and no return type. It is called automatically when: (1) A stack object goes out of scope. (2) delete is called on a heap object. (3) A temporary object is destroyed. Use destructors to release heap memory (delete), close file handles, release locks, or any cleanup your object owns. If your class doesn't manage resources, the compiler generates a correct default destructor automatically.
What is an initializer list in C++ constructors?
An initializer list initializes member variables before the constructor body runs. Syntax: ClassName(int x) : member(x) {} — note the colon. Required for: (1) const data members (cannot be assigned after construction). (2) Reference members (same reason). (3) Members of types with no default constructor. Preferred over assignment in the body for performance: the member is initialized directly rather than default-initialized then assigned. Example: Student(string n, int i) : name(n), id(i) {}
What is the difference between class and struct in C++?
The only technical difference: class defaults to private access; struct defaults to public access. Both support constructors, destructors, methods, inheritance, and all OOP features. Convention: use struct for plain data aggregation (like a Point{x,y} with no invariants); use class when you need encapsulation (private data, public interface). In competitive programming, struct is commonly used for simple record types because typing is shorter.
What is the Rule of Three in C++?
The Rule of Three states: if a class needs to define any one of these, it probably needs to define all three: (1) Destructor (~ClassName), (2) Copy constructor (ClassName(const ClassName&)), (3) Copy assignment operator (ClassName& operator=(const ClassName&)). This rule applies when ever a class manually manages a resource (heap memory, file handle, mutex). Without the copy constructor and assignment operator, the compiler-generated versions do a shallow copy — copying the pointer, not the data, causing double-free bugs.
What is the Rule of Five in C++11?
The Rule of Five extends the Rule of Three to include C++11 move semantics: if you define any of the five, define all five: (1) Destructor, (2) Copy constructor, (3) Copy assignment operator, (4) Move constructor (ClassName(ClassName&&)), (5) Move assignment operator (ClassName& operator=(ClassName&&)). Move operations transfer resources instead of copying them, making class operations on large objects (like dynamic arrays) much faster in con texts like std::vector resizing.
What is the this pointer in C++?
this is a pointer available inside every non-static member function that points to the current object. It's used to: (1) Disambiguate when a parameter shadows a member variable: this->name = name; (2) Return the current object from a method (for method chaining): return *this; (3) Pass the current object to another function. this is a const pointer (can't change what it points to) but for non-const methods, the object itself can be modified through it.
What is a const member function in C++?
A const member function is declared with const after the parameter list: void display() const. It guarantees that calling this function will NOT modify any member variable of the object. This allows const objects and const references to call the function. Best practice: mark any member function that does not modify the object as const — it makes your code self-documenting and enables correct use with const references and const objects.
How do you implement a stack using a class in C++?
class Stack { private: int arr[100]; int top; public: Stack() : top(-1) {} void push(int x) { arr[++top] = x; } int pop() { return arr[top--]; } int peek() const { return arr[top]; } bool isEmpty() const { return top == -1; } int size() const { return top + 1; } }; A class-based stack hides the array and top index (encapsulation), provides a clean interface (push/pop/peek), and can be ext ended (e.g., dynamic resizing with std::vector internally).
How do you implement a linked list using a class in C++?
class LinkedList { private: struct Node { int data; Node* next; Node(int v):data(v),next(nullptr){} }; Node* head; public: LinkedList():head(nullptr){} ~LinkedList(){ while(head){Node* t=head;head=head->next;delete t;} } void insert(int v){Node* n=new Node(v);n->next=head;head=n;} }; Key points: Node is a nested struct (private). head is private — callers cannot corrupt the structure directly. The destructor walks the list freeing every node — essential to prevent memory leaks.
What are common mistakes with C++ classes?
(1) Uninitialized members: int x; in class — x is garbage unless the constructor initializes it. (2) Missing destructor with heap members: class with int* arr; and no ~ClassName() leaks memory. (3) Shallow copy with Rule of Three violation: default copy constructor copies the pointer, not the data — causes double-free. (4) Forgetting const on read-only methods: means const objects and const references cannot call the method. (5) Public data members with no reason: breaks encapsulation. (6) Using assignment in constructor body instead of initializer list for const/reference members — compile error.
What is encapsulation in C++ and how do classes implement it?
Encapsulation bundles data and the functions that operate on it into one unit (a class) and restricts direct access to internal data. In C++: make data members private (hidden), provide public member functions (getters/setters/operations) that access or modify the data with validation. Example: private int speed with public set speed(int s){ if(s>=0) speed=s; } — the setter validates before assigning, which is impossible if speed is public. Encapsulation prevents invalid state and reduces debugging effort.
How do classes differ between C++ and Java?
C++ classes: explicit memory management (constructors/destructors), multiple inheritance, no garbage collector, optional virtual dispatch (must declare virtual), default access is private. Java classes: garbage collection (no manual delete), single class inheritance (interfaces for multiple), all methods are virtual by default, all objects are reference types on the heap, default access is package-private. C++ gives more control and performance; Java gives simpler memory management. In C++ you choose stack vs heap allocation; in Java everything is heap.
When should I use new to create an object in C++?
Use stack allocation (MyClass obj;) when: the object's lifetime should end at the closing brace of the current scope, the object is small/medium in size, and you don't need to share ownership. Use heap allocation (MyClass* p = new MyClass();) when: the object must out live the current scope, the object is very large (stack is typically 1–8 MB), you need polymorphism with a base class pointer, or you need to transfer ownership. In modern C++, prefer std::unique_ptr<MyClass> p = std::make_unique<MyClass>(); over raw new to avoid leaks.
What is a copy constructor in C++ and when is it called?
A copy constructor creates a new object as a copy of an existing one. Signature: ClassName(const ClassName& other). Called when: (1) Initializing from another object: MyClass b = a; (2) Passing an object by value to a function. (3) Returning an object by value from a function. If you don't define one, the compiler generates a default that does member-by-member copying (shallow copy). For classes with raw pointer members, shallow copy means both objects share the same heap data — the first destructor call frees it, the second causes a double-free crash. Define a deep-copy constructor in these cases.
How are classes used in DSA and competitive programming?
In DSA: classes implement Node types (linked list nodes, BST nodes, graph adjacency list nodes), full data structures (Stack, Queue, priority queue, Trie), and algorithm abstractions. In competitive programming: struct (C++ class with public default) is used constantly for graph edges, point types, and custom comparators. A struct Edge { int u, v, w; bool operator<(const Edge& e) const { return w < e.w; } }; enables Kruskal's MST in one sort call. Classes make complex DSA code modular, test able, and reusable.
What are best practices for C++ classes?
(1) Private data, public interface — never expose data members directly unless it's a plain struct. (2) Use initializer lists in constructors. (3) Mark const any method that doesn't modify the object. (4) Follow the Rule of Three/Five when managing resources. (5) Prefer smart pointers (unique_ptr, shared_ptr) over raw new/delete. (6) Use override when overriding virtual functions. (7) Give base classes virtual destructors. (8) Keep classes focused — one class, one responsibility. (9) Write getters that return const references to avoid unnecessary copies.