C++ Object-Oriented Programming โ Classes, Objects & Encapsulation Masterclass
Welcome to Phase 9 (Chapter 9): C++ Object-Oriented Programming โ Classes, Objects & Encapsulation Masterclass! Object-Oriented Programming (OOP) bundles data members and member functions into cohesive class blueprints. In this guide, you will master access specifiers (public, private, protected), const member functions, static members, and the 4 pillars of OOP.
| Pillar | Definition | C++ Implementation |
|---|---|---|
| 1. Encapsulation | Bundling data and methods into a single class unit, hiding internal state. | private data members + public getter/setter methods. |
| 2. Abstraction | Hiding complex implementation details and showing only high-level interface. | Abstract classes with pure virtual functions (virtual void f() = 0;). |
| 3. Inheritance | Deriving new child classes from existing parent base classes to reuse code. | class Derived : public Base { ... }; |
| 4. Polymorphism | Ability to process objects differently based on their runtime data type. | Virtual functions (virtual), function overriding & dynamic dispatch. |
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int age;
double marks;
static inline int totalStudents{0}; // C++17 inline static member
public:
// Constructor with Member Initializer List
Student(std::string studentName, int studentAge, double studentMarks)
: name(studentName), age(studentAge), marks(studentMarks) {
totalStudents++;
}
// Destructor
~Student() { totalStudents--; }
// Const member function (guarantees no modification of data members)
void displayDetails() const {
std::cout << "Student: " << name << " | Age: " << age
<< " | Marks: " << marks << "\n";
}
// Static member function
static int getTotalStudents() { return totalStudents; }
};
int main() {
Student s1("Ravi Kumar", 20, 87.5);
Student s2("Anitha Roy", 21, 92.0);
s1.displayDetails();
s2.displayDetails();
std::cout << "Total Active Students: " << Student::getTotalStudents() << "\n";
return 0;
} Q1: Why mark member functions as const (e.g. void display() const)?
Marking a method const promises that it will not modify any data members. Required when operating on const class objects or const T& references!
Q2: What is the this pointer in C++?
An implicit pointer parameter passed to all non-static member functions that points to the invoking class instance object.
Q3: What is the default access specifier in a C++ class vs struct?
Class members default to private. Struct members default to public.
Q4: How do static data members work in C++?
A static data member is shared across ALL instances of the class (only 1 copy exists in memory).
Q5: What is class composition in C++?
Building complex classes by combining simpler objects as data members ("has-a" relationship), preferred over inheritance ("is-a").