WikiGalaxy

Personalize

C++ OOP Basics

Encapsulation

Encapsulation is the concept of wrapping data and methods that operate on the data within a single unit, known as a class. It helps to protect the data from outside interference and misuse.

Abstraction

Abstraction is the process of hiding the complex reality while exposing only the necessary parts. It helps in reducing programming complexity and effort.

Inheritance

Inheritance is a mechanism where a new class is derived from an existing class. The derived class inherits all the features from the base class and can have additional features of its own.

Polymorphism

Polymorphism allows objects to be treated as instances of their parent class. The most common use of polymorphism is when a parent class reference is used to refer to a child class object.


class Animal {
public:
    virtual void sound() {
        cout << "This is a generic animal sound." << endl;
    }
};

class Dog : public Animal {
public:
    void sound() override {
        cout << "Woof Woof" << endl;
    }
};

int main() {
    Animal* animal = new Dog();
    animal->sound(); // Outputs: Woof Woof
    delete animal;
}
    

Classes and Objects

Classes are blueprints for creating objects. An object is an instance of a class. Classes encapsulate data for the object and methods to manipulate that data.

Constructors and Destructors

Constructors are special class functions which perform initialization of every object. The destructor is a special member function that is executed when an object of the class goes out of scope.

Console Output:

Woof Woof

Advanced C++ OOP Concepts

Operator Overloading

Operator overloading allows you to redefine the way operators work for user-defined types. This enhances the readability of the code.

Friend Functions

Friend functions are functions that are allowed to access private and protected members of a class. They are not member functions but can be useful in certain situations.

Virtual Functions

Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for the function call.

Pure Virtual Functions

A pure virtual function is a function that has no implementation in the base class and must be implemented in derived classes. It makes a class abstract.


#include 
using namespace std;

class Base {
public:
    virtual void show() = 0; // Pure virtual function
};

class Derived : public Base {
public:
    void show() {
        cout << "Implementation of pure virtual function in Derived class." << endl;
    }
};

int main() {
    Derived d;
    d.show(); // Outputs: Implementation of pure virtual function in Derived class.
    return 0;
}
    

Multiple Inheritance

Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. However, it can lead to ambiguity if not managed properly.

Templates

Templates in C++ allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

Console Output:

Implementation of pure virtual function in Derived class.

C++ OOP Design Principles

Single Responsibility Principle

A class should have only one reason to change, meaning that a class should only have one job or responsibility.

Open/Closed Principle

Software entities should be open for extension but closed for modification. This means that the behavior of a module can be extended without modifying its source code.

Liskov Substitution Principle

Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.

Interface Segregation Principle

Clients should not be forced to depend upon interfaces that they do not use. This principle suggests that many client-specific interfaces are better than one general-purpose interface.


#include 
using namespace std;

class Shape {
public:
    virtual void draw() = 0;
};

class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing Circle" << endl;
    }
};

void renderShape(Shape* shape) {
    shape->draw();
}

int main() {
    Circle circle;
    renderShape(&circle); // Outputs: Drawing Circle
    return 0;
}
    

Dependency Inversion Principle

High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.

Console Output:

Drawing Circle

C++ OOP and Memory Management

Dynamic Memory Allocation

Dynamic memory allocation allows the program to request memory at runtime using operators like new and delete. This is crucial for managing resources efficiently.

Smart Pointers

Smart pointers are objects which store pointers to dynamically allocated (heap) objects. They help in automatic and deterministic destruction of dynamically allocated objects.


#include 
#include 
using namespace std;

class Resource {
public:
    Resource() { cout << "Resource acquired" << endl; }
    ~Resource() { cout << "Resource destroyed" << endl; }
};

int main() {
    {
        unique_ptr res(new Resource());
    } // Resource is destroyed here as it goes out of scope
    return 0;
}
    

RAII (Resource Acquisition Is Initialization)

RAII is a programming idiom which ensures that resources are properly released when they are no longer needed. This is achieved by tying resources to the lifespan of objects.

Console Output:

Resource acquired Resource destroyed

C++ OOP and Exception Handling

Exception Handling Basics

Exception handling in C++ is done using try, catch, and throw keywords. It allows a program to deal with unexpected situations gracefully.

Custom Exceptions

Custom exceptions can be created by inheriting from the standard exception class. This allows you to define your own exception types for specific error conditions.


#include 
#include 
using namespace std;

class MyException : public exception {
public:
    const char* what() const noexcept override {
        return "My custom exception";
    }
};

int main() {
    try {
        throw MyException();
    } catch (const MyException& e) {
        cout << e.what() << endl;
    }
    return 0;
}
    

Stack Unwinding

Stack unwinding is the process during exception handling where the stack is cleaned up as the control is transferred to the exception handler. This ensures that resources are released properly.

Console Output:

My custom exception

C++ OOP and Design Patterns

Singleton Pattern

The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. This is useful when exactly one object is needed to coordinate actions across the system.

Factory Pattern

The Factory pattern defines an interface for creating an object, but lets subclasses alter the type of objects that will be created. It promotes loose coupling by eliminating the need to bind application-specific classes into the code.


#include 
using namespace std;

class Singleton {
private:
    static Singleton* instance;
    Singleton() {}
public:
    static Singleton* getInstance() {
        if (!instance)
            instance = new Singleton();
        return instance;
    }
    void showMessage() {
        cout << "Singleton Instance" << endl;
    }
};

Singleton* Singleton::instance = nullptr;

int main() {
    Singleton* s = Singleton::getInstance();
    s->showMessage(); // Outputs: Singleton Instance
    return 0;
}
    

Observer Pattern

The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Console Output:

Singleton Instance

C++ OOP and Multithreading

Thread Management

C++ provides a thread class that represents a single thread of execution. Threads can be created by passing a function to the thread constructor.

Mutexes and Locks

Mutexes are used to protect shared data from being simultaneously accessed by multiple threads. Locks provide a convenient RAII-style mechanism for owning a mutex for the duration of a scoped block.


#include 
#include 
#include 
using namespace std;

mutex mtx;

void print_even(int n) {
    lock_guard lock(mtx);
    if (n % 2 == 0) {
        cout << n << " is even" << endl;
    }
}

void print_odd(int n) {
    lock_guard lock(mtx);
    if (n % 2 != 0) {
        cout << n << " is odd" << endl;
    }
}

int main() {
    thread t1(print_even, 10);
    thread t2(print_odd, 9);

    t1.join();
    t2.join();

    return 0;
}
    

Condition Variables

Condition variables are synchronization primitives that enable threads to wait until a particular condition occurs. They are used in conjunction with mutexes.

Console Output:

10 is even 9 is odd

C++ OOP and File Handling

File Streams

C++ provides file stream classes to perform file operations like reading and writing. These classes include ifstream, ofstream, and fstream.

Reading and Writing Files

Files can be read and written using the file stream classes. The file stream is opened using the open() method, and the data is read or written using the stream insertion and extraction operators.


#include 
#include 
using namespace std;

int main() {
    ofstream outfile("example.txt");
    outfile << "Hello, File!" << endl;
    outfile.close();

    ifstream infile("example.txt");
    string content;
    getline(infile, content);
    cout << content << endl;
    infile.close();

    return 0;
}
    

File Positioning

File positioning functions such as seekg(), seekp(), tellg(), and tellp() are used to move the file pointer to a specific location and to determine the current position of the file pointer.

Console Output:

Hello, File!

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025