cpp
OOP Basics
05_OOP_Basics⚙️cpp
/**
* ============================================================
* C++ CLASSES - FUNDAMENTALS
* ============================================================
*
* This file covers:
* - Class declaration
* - Data members and member functions
* - Access specifiers
* - Constructors and destructors
* - The this pointer
*
* Compile: g++ -std=c++17 -Wall 01_classes.cpp -o classes
* Run: ./classes
*
* ============================================================
*/
#include <iostream>
#include <string>
using namespace std;
// ============================================================
// PART 1: BASIC CLASS DEFINITION
// ============================================================
/*
* A CLASS is a blueprint for creating objects.
* It encapsulates:
* - Data (member variables/attributes)
* - Behavior (member functions/methods)
*/
// Simple class definition
class Rectangle {
// By default, members are private
double width;
double height;
public: // Access specifier
// Member function to set dimensions
void setDimensions(double w, double h) {
width = w;
height = h;
}
// Member function to calculate area
double getArea() {
return width * height;
}
// Member function to calculate perimeter
double getPerimeter() {
return 2 * (width + height);
}
};
// ============================================================
// PART 2: CLASS WITH CONSTRUCTORS
// ============================================================
class Person {
private:
string name;
int age;
public:
// Default constructor
Person() {
name = "Unknown";
age = 0;
cout << " Default constructor called" << endl;
}
// Parameterized constructor
Person(string n, int a) {
name = n;
age = a;
cout << " Parameterized constructor called for " << name << endl;
}
// Constructor with member initializer list (preferred!)
Person(string n) : name(n), age(0) {
cout << " Initializer list constructor called for " << name << endl;
}
// Destructor
~Person() {
cout << " Destructor called for " << name << endl;
}
// Getter methods
string getName() const { return name; }
int getAge() const { return age; }
// Setter methods
void setName(const string& n) { name = n; }
void setAge(int a) {
if (a >= 0) age = a; // Validation
}
// Display method
void display() const {
cout << " Name: " << name << ", Age: " << age << endl;
}
};
// ============================================================
// PART 3: ACCESS SPECIFIERS
// ============================================================
class BankAccount {
private: // Only accessible within the class
string accountNumber;
double balance;
protected: // Accessible in class and derived classes
string accountType;
public: // Accessible from anywhere
// Constructor
BankAccount(string accNum, double initialBalance)
: accountNumber(accNum), balance(initialBalance), accountType("Regular") {}
// Public interface
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << " Deposited: $" << amount << endl;
}
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << " Withdrawn: $" << amount << endl;
return true;
}
cout << " Withdrawal failed!" << endl;
return false;
}
double getBalance() const {
return balance;
}
void displayInfo() const {
cout << " Account: " << accountNumber << endl;
cout << " Type: " << accountType << endl;
cout << " Balance: $" << balance << endl;
}
};
// ============================================================
// PART 4: THE 'this' POINTER
// ============================================================
class Counter {
private:
int count;
public:
Counter() : count(0) {}
// 'this' is a pointer to the current object
Counter& increment() {
this->count++;
return *this; // Return reference for chaining
}
Counter& decrement() {
this->count--;
return *this;
}
Counter& add(int value) {
count += value;
return *this;
}
// When parameter name matches member name
void setCount(int count) {
this->count = count; // this->count is member, count is parameter
}
int getCount() const { return count; }
};
// ============================================================
// PART 5: CONST MEMBER FUNCTIONS
// ============================================================
class Point {
private:
double x, y;
public:
Point(double x = 0, double y = 0) : x(x), y(y) {}
// Const member function - cannot modify object
double getX() const { return x; }
double getY() const { return y; }
// Non-const - can modify object
void setX(double newX) { x = newX; }
void setY(double newY) { y = newY; }
// Const - promises not to modify object
void display() const {
cout << "(" << x << ", " << y << ")";
// x = 10; // ERROR: can't modify in const function
}
// Distance from origin (const - doesn't modify)
double distanceFromOrigin() const {
return sqrt(x*x + y*y);
}
};
// ============================================================
// PART 6: STRUCT VS CLASS
// ============================================================
// struct: members are public by default
struct PointStruct {
double x, y; // Public by default
void display() {
cout << "(" << x << ", " << y << ")";
}
};
// class: members are private by default
class PointClass {
double x, y; // Private by default
public:
void setX(double newX) { x = newX; }
void setY(double newY) { y = newY; }
};
// ============================================================
// MAIN FUNCTION
// ============================================================
int main() {
cout << "============================================" << endl;
cout << " C++ CLASSES - FUNDAMENTALS" << endl;
cout << "============================================" << endl << endl;
// ========================================================
// DEMO 1: Basic Class Usage
// ========================================================
cout << "--- DEMO 1: BASIC CLASS ---" << endl << endl;
Rectangle rect;
rect.setDimensions(5.0, 3.0);
cout << "Rectangle (5 x 3):" << endl;
cout << " Area: " << rect.getArea() << endl;
cout << " Perimeter: " << rect.getPerimeter() << endl;
cout << endl;
// ========================================================
// DEMO 2: Constructors and Destructors
// ========================================================
cout << "--- DEMO 2: CONSTRUCTORS & DESTRUCTOR ---" << endl << endl;
cout << "Creating p1 (default constructor):" << endl;
Person p1;
p1.display();
cout << "\nCreating p2 (parameterized constructor):" << endl;
Person p2("Alice", 25);
p2.display();
cout << "\nCreating p3 (initializer list constructor):" << endl;
Person p3("Bob");
p3.display();
cout << "\nUsing setters:" << endl;
p1.setName("Charlie");
p1.setAge(30);
p1.display();
cout << "\nScope ending, destructors will be called:" << endl;
{
Person temp("Temp", 20);
}
cout << "Temp destroyed" << endl;
cout << endl;
// ========================================================
// DEMO 3: Encapsulation
// ========================================================
cout << "--- DEMO 3: ENCAPSULATION ---" << endl << endl;
BankAccount account("123456", 1000.0);
account.displayInfo();
cout << "\nOperations:" << endl;
account.deposit(500);
account.withdraw(200);
account.withdraw(2000); // Should fail
cout << "\nFinal balance: $" << account.getBalance() << endl;
// account.balance = 1000000; // ERROR: balance is private!
cout << endl;
// ========================================================
// DEMO 4: The 'this' Pointer
// ========================================================
cout << "--- DEMO 4: THE 'this' POINTER ---" << endl << endl;
Counter counter;
// Method chaining using 'this'
counter.increment()
.increment()
.increment()
.add(10)
.decrement();
cout << "After chained operations: " << counter.getCount() << endl;
counter.setCount(100);
cout << "After setCount(100): " << counter.getCount() << endl;
cout << endl;
// ========================================================
// DEMO 5: Const Member Functions
// ========================================================
cout << "--- DEMO 5: CONST MEMBER FUNCTIONS ---" << endl << endl;
Point p(3, 4);
cout << "Point p: ";
p.display();
cout << endl;
cout << "Distance from origin: " << p.distanceFromOrigin() << endl;
// Const object can only call const member functions
const Point constPoint(5, 12);
cout << "Const point distance: " << constPoint.distanceFromOrigin() << endl;
// constPoint.setX(10); // ERROR: can't call non-const on const object
cout << endl;
// ========================================================
// DEMO 6: Struct vs Class
// ========================================================
cout << "--- DEMO 6: STRUCT VS CLASS ---" << endl << endl;
// struct - direct access to members
PointStruct ps;
ps.x = 10; // Direct access (public by default)
ps.y = 20;
cout << "Struct point: ";
ps.display();
cout << endl;
// class - use methods to access
PointClass pc;
pc.setX(10); // Must use setter (x is private)
pc.setY(20);
cout << "\nstruct vs class:" << endl;
cout << "• struct: members public by default" << endl;
cout << "• class: members private by default" << endl;
cout << "• Otherwise identical in C++" << endl;
cout << endl;
// ========================================================
// CLASS SUMMARY
// ========================================================
cout << "--- CLASS CONCEPTS SUMMARY ---" << endl << endl;
cout << "Class Structure:" << endl;
cout << "─────────────────────────────────────────" << endl;
cout << "class ClassName {" << endl;
cout << "private:" << endl;
cout << " // Data members" << endl;
cout << " int data;" << endl;
cout << " " << endl;
cout << "public:" << endl;
cout << " // Constructor" << endl;
cout << " ClassName() : data(0) {}" << endl;
cout << " " << endl;
cout << " // Destructor" << endl;
cout << " ~ClassName() {}" << endl;
cout << " " << endl;
cout << " // Member functions" << endl;
cout << " int getData() const { return data; }" << endl;
cout << " void setData(int d) { data = d; }" << endl;
cout << "};" << endl;
cout << "\nAccess Specifiers:" << endl;
cout << "• private: Only class members" << endl;
cout << "• protected: Class and derived classes" << endl;
cout << "• public: Everyone" << endl;
cout << endl;
cout << "============================================" << endl;
cout << "Destructors being called for p1, p2, p3..." << endl;
cout << "============================================" << endl;
return 0;
}
// ============================================================
// EXERCISES:
// ============================================================
/*
* 1. Create a 'Book' class with:
* - Private: title, author, price, pages
* - Constructors: default and parameterized
* - Getters and setters
* - Display function
*
* 2. Create a 'Time' class with:
* - Private: hours, minutes, seconds
* - Validation in setters
* - addSeconds() method
* - display() in HH:MM:SS format
*
* 3. Create a 'Student' class with:
* - Private: name, id, grades array
* - Method to add grade
* - Method to calculate average
* - Method to display transcript
*
* 4. Create a 'Vector2D' class with:
* - Private: x, y
* - Methods for add, subtract, dot product
* - Method chaining support
*/