Object-Oriented C++
intermediateWhat You'll Learn
Theory
C++ supports object-oriented programming with classes, inheritance, polymorphism, and encapsulation. Its OOP model gives fine-grained control over memory and behavior.
Classes and Objects
A class is a user-defined type that bundles data and functions together:
class Rectangle {
public:
double width;
double height;
double getArea() {
return width * height;
}
};
Rectangle rect;
rect.width = 5.0;
rect.height = 3.0;Access Specifiers
public— accessible from anywhereprivate— accessible only within the class (default for classes)protected— accessible in the class and derived classes
Encapsulation is achieved by making data private and providing public getter/setter methods.
References vs Pointers
A reference (&) is an alias to an existing variable. Unlike pointers, references cannot be null and cannot be reassigned:
int x = 10;
int& ref = x; // ref is an alias for x
ref = 20; // x is now 20References are commonly used for efficient parameter passing without copying.
Why this matters
Object-oriented programming in C++ gives you fine-grained control over memory and behavior while keeping code organized and reusable. Encapsulation, access control, and references are fundamental to writing safe, efficient C++ code.
What's next
In the next lessons, you'll dive deeper into each topic with hands-on examples and exercises.
Exercises
Product Class with Encapsulation
Create a Product class with private fields (name, price, quantity), a constructor, getters, and a method to calculate total value (price * quantity).
Expected Output:
Product: Widget, Price: $19.99, Quantity: 10, Total Value: $199.90