This is the turning point in your C++ journey. Object-Oriented Programming (OOP) is a paradigm where you view your program as a collection of "Objects" that interact with each other, rather than just a list of instructions.
1. The Class (The Blueprint)
A Class is a user-defined data type that acts as a template. It defines what data an object will hold and what actions it can perform.
2. The Object (The House)
If a class is the blueprint for a house, the Object is the actual house built from that blueprint. You can build many houses (objects) from one blueprint (class).
3. Access Specifiers
In OOP, we control who can see the data:
public: Members are accessible from outside the class.private: Members can only be accessed by functions inside that specific class. (This is the "Safety" feature).
Code Example: Building a Smartphone Class
This program defines a Smartphone class with data (attributes) and functions (methods).
#include <iostream>
#include <string>
using namespace std;
class Smartphone {
public:
// Attributes (Variables)
string model;
int storage;
double price;
// Methods (Functions inside a class)
void makeCall() {
cout << "Connecting call from " << model << "..." << endl;
}
void showSpecs() {
cout << "Model: " << model << "\nStorage: " << storage << "GB" << endl;
cout << "Price: $" << price << endl;
}
};
int main() {
// 1. Create an Object of the class
Smartphone myPhone;
// 2. Set attributes
myPhone.model = "iPhone 15";
myPhone.storage = 256;
myPhone.price = 999.99;
// 3. Call methods
myPhone.showSpecs();
myPhone.makeCall();
// 4. Create another object
Smartphone oldPhone;
oldPhone.model = "Nokia 3310";
oldPhone.makeCall();
return 0;
}Why use Classes over Structs?
While they look similar, classes are designed for Encapsulation. You can hide sensitive data (like a password) as private and only allow it to be changed through a public function that checks for errors first.