Module 14: Object-Oriented ProgrammingIntermediate55 min read
Classes, Objects, Encapsulation, Constructors & Destructors
Build well-encapsulated C++ classes with public/private/protected access specifiers, default/parameterized/copy/move constructors, initializer lists, and destructors.
Key Takeaways & Core Concepts
- Member Initializer List:
User(std::string n) : name(std::move(n)) {}initializes members directly (required forconstand reference members). - Delegating Constructors (C++11): One constructor forwards to another.
- Copy / Move Constructors & Destructor: If a class manages a raw resource, follow the Rule of 5 (Destructor, Copy Ctor, Copy Assign, Move Ctor, Move Assign). Better yet, use smart pointers/STL and follow the Rule of 0!
1. Encapsulation, Access Specifiers & `this` Pointer
A class bundles state (data members) and behavior (member functions) behind private, protected, and public access specifiers. Inside non-static member functions, the implicit this pointer points to the invoking instance.
1. Encapsulation, Static Counter & Const Method
1#include <iostream>
2#include <string>
3
4class Student {
5 std::string name;
6 int score;
7 static inline int totalStudents = 0; // C++17 inline static
8public:
9 Student(std::string n, int s) : name(std::move(n)), score(s) { ++totalStudents; }
10 void print() const { std::cout << name << ": " << score << "\n"; }
11 static int count() { return totalStudents; }
12};
13
14int main() {
15 const Student s1("Ananya", 94);
16 Student s2("Rohan", 89);
17 s1.print();
18 std::cout << "Total students: " << Student::count() << "\n";
19 return 0;
20}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
20 lines
Note: `const Student s1` can call `print()` because it is marked `const`; `totalStudents` is shared across instances.
2. Constructors, Initializer Lists & Rule of 0 / 3 / 5
- Member Initializer List:
User(std::string n) : name(std::move(n)) {}initializes members directly (required forconstand reference members). - Delegating Constructors (C++11): One constructor forwards to another.
- Copy / Move Constructors & Destructor: If a class manages a raw resource, follow the Rule of 5 (Destructor, Copy Ctor, Copy Assign, Move Ctor, Move Assign). Better yet, use smart pointers/STL and follow the Rule of 0!
3. `const` Member Functions, `static` & `friend`
Mark read-only getters const so they can be called on const objects. static members belong to the class itself; friend grants controlled access to private internals.
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)