TutorialsC++OOP Basics
Share:

OOP Basics

intermediate

Part of Object-Oriented C++

Theory

Object-Oriented Programming (OOP) is a programming paradigm that organizes code around objects — entities that combine data (attributes) and behavior (methods). C++ fully supports OOP with classes, inheritance, polymorphism, and encapsulation.

Class vs Object

A class is a blueprint or template. An object is an instance of that class.

// Class definition
class Car {
public:
    string brand;
    string model;
    int year;
 
    void start() {
        cout << "The car is starting..." << endl;
    }
};
 
// Creating objects
Car myCar;          // Object
myCar.brand = "Toyota";
myCar.start();

Access Specifiers

Access specifiers control who can access class members:

| Specifier | Same Class | Derived Class | Outside | |-----------|-----------|---------------|---------| | public | ✓ | ✓ | ✓ | | protected| ✓ | ✓ | ✗ | | private | ✓ | ✗ | ✗ |

class BankAccount {
private:
    double balance;     // Only accessible within the class
 
protected:
    string accountNumber;  // Accessible in derived classes
 
public:
    string ownerName;   // Accessible everywhere
 
    void deposit(double amount) {
        if (amount > 0) balance += amount;
    }
};

By default, all members of a class are private.

Constructors

A constructor is a special member function that runs automatically when an object is created. It has the same name as the class and no return type.

Default constructor — no parameters:

class Student {
public:
    string name;
    int age;
 
    Student() {
        name = "Unknown";
        age = 0;
    }
};

Parameterized constructor:

class Student {
public:
    string name;
    int age;
 
    Student(string n, int a) : name(n), age(a) {
        // Constructor body
    }
};

Copy constructor — creates an object as a copy of another:

class Student {
public:
    string name;
    int age;
 
    // Copy constructor
    Student(const Student& other) : name(other.name), age(other.age) {
        cout << "Copy constructor called" << endl;
    }
};

Destructor (~)

A destructor runs automatically when an object is destroyed. It has the same name as the class prefixed with ~, no parameters, and no return type:

class FileHandler {
private:
    ifstream* file;
 
public:
    FileHandler(string filename) {
        file = new ifstream(filename);
    }
 
    ~FileHandler() {
        delete file;  // Clean up dynamically allocated memory
        cout << "File closed." << endl;
    }
};

Destructors are essential for RAII (Resource Acquisition Is Initialization) — a core C++ idiom where resources are tied to object lifetime.

The this Pointer

this is a pointer to the current object instance. It is used to:

  • Resolve naming conflicts
  • Chain method calls
class Person {
private:
    string name;
 
public:
    Person& setName(string name) {
        this->name = name;  // this->name refers to the member
        return *this;       // Return reference for chaining
    }
 
    void greet() {
        cout << "Hi, I'm " << this->name << endl;
    }
};
 
// Method chaining
Person p;
p.setName("Alice").greet();  // setName returns reference to p

Friend Function

A friend function is a non-member function that has access to a class's private and protected members:

class Rectangle {
private:
    double width, height;
 
public:
    Rectangle(double w, double h) : width(w), height(h) {}
 
    // Friend function declaration
    friend double area(const Rectangle& rect);
};
 
// Friend function definition
double area(const Rectangle& rect) {
    return rect.width * rect.height;  // Accessing private members
}
 
int main() {
    Rectangle r(5, 3);
    cout << "Area: " << area(r) << endl;  // 15
    return 0;
}

Static Members

Static members belong to the class itself, not to individual objects:

class Counter {
private:
    static int count;  // Static member declaration
 
public:
    Counter() { count++; }
    ~Counter() { count--; }
 
    static int getCount() { return count; }
};
 
// Static member definition (required outside the class)
int Counter::count = 0;
 
int main() {
    Counter c1, c2;
    cout << Counter::getCount();  // 2
    {
        Counter c3;
        cout << Counter::getCount();  // 3
    }
    cout << Counter::getCount();  // 2 (c3 destroyed)
}

Const Member Functions

A const member function promises not to modify the object:

class Point {
private:
    int x, y;
 
public:
    Point(int x, int y) : x(x), y(y) {}
 
    int getX() const { return x; }  // Cannot modify x
    int getY() const { return y; }
 
    void setX(int newX) { x = newX; }  // Non-const
};
 
void printPoint(const Point& p) {
    cout << p.getX() << ", " << p.getY();  // OK — const methods
    // p.setX(10);  // Error! Cannot call non-const on const ref
}

Encapsulation

Encapsulation hides internal data and exposes a public interface. This is achieved by making data members private and providing public getters/setters:

class Temperature {
private:
    double celsius;
 
public:
    void setCelsius(double c) { celsius = c; }
 
    void setFahrenheit(double f) {
        celsius = (f - 32.0) * 5.0 / 9.0;
    }
 
    double getCelsius() const { return celsius; }
 
    double getFahrenheit() const {
        return celsius * 9.0 / 5.0 + 32.0;
    }
};

The rule of three/five: if you define a custom destructor, copy constructor, or copy assignment operator, you likely need all three (or five with move semantics). This is due to resource management requirements.

Practical Examples

Example 1: Complete Class with Encapsulation
cpp
Example 2: RAII with File Handling
cpp

Use the = default syntax to explicitly request the compiler-generated default constructor or special member functions. Use = delete to disable functions you don't want.

Exercises

Create a Book Class

easy

Create a Book class with private fields: title, author, and pages. Include a parameterized constructor, getters, a method displayInfo(), and a const method isLong() that returns true if pages > 300.

Expected Output:

Title: 1984\nAuthor: George Orwell\nPages: 328\nLong book: Yes

Bank Account with Static Members

medium

Create a BankAccount class with: accountNumber (auto-generated static counter), ownerName, balance. Include deposit(), withdraw(), display() methods. Track total number of accounts and total money in the banking system using static members.

Expected Output:

Account #1 Alice: $1200.00\nAccount #2 Bob: $400.00\nTotal accounts: 2\nTotal balance: $1600.00

Vector3D with Friend Functions

hard

Create a Vector3D class with x, y, z coordinates. Implement operator overloading (+, -, *) using friend functions. Also implement dot product, cross product, and magnitude calculation.

Expected Output:

v1: (1, 2, 3)\nv2: (4, 5, 6)\nSum: (5, 7, 9)\nDiff: (-3, -3, -3)\nScaled: (2.5, 5, 7.5)\nDot: 32

Mini Quiz

Mini Quiz

Mini Project

Mini Project: Inventory Management System

Build an inventory management system using classes. Implement Product and Inventory classes with proper encapsulation, static members, const correctness, and RAII principles.

Requirements:

    Bonus Challenge

    Add file I/O: save the inventory to a file on destruction and load it on construction. Add a low-stock alert feature.