MODULE 6: OBJECT-ORIENTED PROGRAMMING (OOP) 6.6 C++ Abstraction (Abstract Classes, Interfaces, Information Hiding)

Industrial reference manual: Comprehensive architectural breakdown of C++ Abstraction, abstract classes, pure virtual interfaces, information hiding, decoupling system components, and 10 production-aligned real-world implementations with outputs.

🎭 Mastering Abstraction: Hiding Complexity & Defining Contracts

Abstraction is the concept of exposing only essential features of a system while hiding background implementation details. In C++, abstraction is implemented primarily using **Abstract Classes** and **Pure Virtual Functions** (`= 0`), which establish strict contracts that derived classes must fulfill.

📜 Abstract Classes & Interfaces

  • Abstract Class: A class containing at least one pure virtual function. It cannot be instantiated directly.
  • Interface: An abstract class consisting solely of pure virtual functions, defining public behavioral contracts.
  • Enforced Implementation: Derived classes *must* override all pure virtual functions to compile.

💡 Key Engineering Benefits

  • Decoupling: High-level modules interact with interfaces rather than concrete implementations.
  • Maintainability: Simplifies complex subsystems into clean, uniform API contracts.

📊 End-to-End Abstract Interface Contract & Concrete Implementation Workflow Diagram

1. Interface Contract

Define abstract base class with pure virtual methods (`= 0`).

→

2. Client Integration

Client code interacts exclusively with abstract interface pointers.

→

3. Concrete Subclass

Derived class overrides and implements pure virtual contract methods.

↓

6. Console Rendering

Display execution output via `std::cout` stream.

←

5. Method Execution

Executes concrete business logic specific to subclass implementation.

←

4. Dynamic Dispatch

Calls resolved at runtime via virtual table (vtable).

1. Payment Gateway Interface Abstraction (Stripe vs PayPal)
Defines a payment gateway abstract interface, allowing checkout systems to process payments without knowing gateway specifics.
C++ / Payment Gateway Abstraction
#include 
#include 
#include 

using namespace std;

// Abstract Interface
class PaymentGateway {
public:
    virtual void authorizePayment(double amount) = 0;
    virtual void capturePayment() = 0;
    virtual ~PaymentGateway() {}
};

class StripeGateway : public PaymentGateway {
public:
    void authorizePayment(double amount) override {
        cout << "[Stripe]: Authorized ₹" << amount << " via Credit Card." << endl;
    }
    void capturePayment() override {
        cout << "[Stripe]: Payment captured successfully." << endl;
    }
};

int main() {
    cout << "--- Payment Gateway Abstraction ---" << endl;
    unique_ptr gateway = make_unique();
    
    gateway->authorizePayment(4999.00);
    gateway->capturePayment();
    return 0;
}
--- Payment Gateway Abstraction --- [Stripe]: Authorized ₹4999 via Credit Card. [Stripe]: Payment captured successfully.
2. Database Driver Abstraction (MySQL vs PostgreSQL)
Hides specific database wire protocols behind a unified `DatabaseDriver` abstract interface.
C++ / Database Driver Abstraction
#include 
#include 
#include 

using namespace std;

class DatabaseDriver {
public:
    virtual void connect(string connStr) = 0;
    virtual void query(string sql) = 0;
    virtual ~DatabaseDriver() {}
};

class MySqlDriver : public DatabaseDriver {
public:
    void connect(string connStr) override {
        cout << "[MySQL]: Connected to server -> " << connStr << endl;
    }
    void query(string sql) override {
        cout << "[MySQL Query]: " << sql << endl;
    }
};

int main() {
    cout << "--- Database Driver Abstraction ---" << endl;
    unique_ptr db = make_unique();
    db->connect("mysql://localhost:3306/nikitadb");
    db->query("SELECT * FROM products");
    return 0;
}
--- Database Driver Abstraction --- [MySQL]: Connected to server -> mysql://localhost:3306/nikitadb [MySQL Query]: SELECT * FROM products
3. Smart Home Appliance Interface Abstraction
Defines a unified `SmartAppliance` abstract interface controlling lights, fans, and locks.
C++ / Smart Home Abstraction
#include 
#include 

using namespace std;

class SmartAppliance {
public:
    virtual void turnOn() = 0;
    virtual void turnOff() = 0;
    virtual ~SmartAppliance() {}
};

class SmartLight : public SmartAppliance {
public:
    void turnOn() override { cout << "[Smart Light]: Powered ON (100% brightness)." << endl; }
    void turnOff() override { cout << "[Smart Light]: Powered OFF." << endl; }
};

int main() {
    cout << "--- Smart Home Abstraction ---" << endl;
    unique_ptr light = make_unique();
    light->turnOn();
    light->turnOff();
    return 0;
}
--- Smart Home Abstraction --- [Smart Light]: Powered ON (100% brightness). [Smart Light]: Powered OFF.
4. Cloud Storage Provider Abstraction (AWS S3 vs Google Cloud)
Abstracts cloud file uploads so application code remains agnostic of underlying storage vendors.
C++ / Cloud Storage Abstraction
#include 
#include 
#include 

using namespace std;

class CloudStorage {
public:
    virtual void uploadFile(string fileName) = 0;
    virtual void downloadFile(string fileName) = 0;
    virtual ~CloudStorage() {}
};

class AwsS3Storage : public CloudStorage {
public:
    void uploadFile(string fileName) override {
        cout << "[AWS S3]: Uploading '" << fileName << "' to bucket 'nikita-bucket'." << endl;
    }
    void downloadFile(string fileName) override {
        cout << "[AWS S3]: Downloading '" << fileName << "'." << endl;
    }
};

int main() {
    cout << "--- Cloud Storage Abstraction ---" << endl;
    unique_ptr storage = make_unique();
    storage->uploadFile("architecture_diagram.pdf");
    return 0;
}
--- Cloud Storage Abstraction --- [AWS S3]: Uploading 'architecture_diagram.pdf' to bucket 'nikita-bucket'.
5. Graphic Rendering Engine Abstraction
Abstracts graphics rendering pipelines (OpenGL vs DirectX) through a common drawing interface.
C++ / Graphics Engine Abstraction
#include 
#include 
#include 

using namespace std;

class RenderEngine {
public:
    virtual void drawMesh(string meshName) = 0;
    virtual void renderFrame() = 0;
    virtual ~RenderEngine() {}
};

class OpenGlEngine : public RenderEngine {
public:
    void drawMesh(string meshName) override {
        cout << "[OpenGL]: Drawing 3D mesh -> " << meshName << endl;
    }
    void renderFrame() override {
        cout << "[OpenGL]: Swapping frame buffers." << endl;
    }
};

int main() {
    cout << "--- Graphics Engine Abstraction ---" << endl;
    unique_ptr engine = make_unique();
    engine->drawMesh("CharacterModel.fbx");
    engine->renderFrame();
    return 0;
}
--- Graphics Engine Abstraction --- [OpenGL]: Drawing 3D mesh -> CharacterModel.fbx [OpenGL]: Swapping frame buffers.
6. Notification Dispatcher Abstraction (SMS, Email, Push)
Enforces a notification delivery contract, abstracting message delivery protocols.
C++ / Notification Dispatcher Abstraction
#include 
#include 
#include 

using namespace std;

class NotificationChannel {
public:
    virtual void sendAlert(string recipient, string message) = 0;
    virtual ~NotificationChannel() {}
};

class SmsChannel : public NotificationChannel {
public:
    void sendAlert(string recipient, string message) override {
        cout << "[SMS to " << recipient << "]: " << message << endl;
    }
};

int main() {
    cout << "--- Notification Abstraction ---" << endl;
    unique_ptr sms = make_unique();
    sms->sendAlert("+919876543210", "Your OTP is 9812.");
    return 0;
}
--- Notification Abstraction --- [SMS to +919876543210]: Your OTP is 9812.
7. Vehicle Transmission Controller Abstraction
Abstracts automatic and manual gear shifting mechanics behind a standardized interface.
C++ / Transmission Controller Abstraction
#include 
#include 

using namespace std;

class TransmissionController {
public:
    virtual void shiftGear(int gear) = 0;
    virtual void engageClutch() = 0;
    virtual ~TransmissionController() {}
};

class AutomaticTransmission : public TransmissionController {
public:
    void shiftGear(int gear) override {
        cout << "[Automatic]: Hydraulic actuators shifted to gear " << gear << endl;
    }
    void engageClutch() override {
        cout << "[Automatic]: Torque converter engaged automatically." << endl;
    }
};

int main() {
    cout << "--- Transmission Abstraction ---" << endl;
    unique_ptr tx = make_unique();
    tx->engageClutch();
    tx->shiftGear(3);
    return 0;
}
--- Transmission Abstraction --- [Automatic]: Torque converter engaged automatically. [Automatic]: Hydraulic actuators shifted to gear 3
8. Logging System Abstraction (File vs Console vs Cloud)
Abstracts application logging targets so logs can be routed to files or cloud servers transparently.
C++ / Logger Abstraction
#include 
#include 
#include 

using namespace std;

class Logger {
public:
    virtual void writeLog(string level, string message) = 0;
    virtual ~Logger() {}
};

class ConsoleLogger : public Logger {
public:
    void writeLog(string level, string message) override {
        cout << "[" << level << "] " << message << endl;
    }
};

int main() {
    cout << "--- Logger Abstraction ---" << endl;
    unique_ptr logger = make_unique();
    logger->writeLog("INFO", "Application boot sequence completed.");
    return 0;
}
--- Logger Abstraction --- [INFO]: Application boot sequence completed.
9. IoT Sensor Telemetry Device Abstraction
Abstracts various environmental sensors (temperature, pressure, humidity) behind a unified telemetry interface.
C++ / Sensor Telemetry Abstraction
#include 
#include 
#include 

using namespace std;

class SensorNode {
public:
    virtual double readSensorValue() = 0;
    virtual string getSensorUnit() = 0;
    virtual ~SensorNode() {}
};

class TemperatureSensor : public SensorNode {
public:
    double readSensorValue() override {
        return 28.5; // Simulated reading
    }
    string getSensorUnit() override {
        return "°C";
    }
};

int main() {
    cout << "--- Sensor Telemetry Abstraction ---" << endl;
    unique_ptr sensor = make_unique();
    cout << "Live Sensor Reading: " << sensor->readSensorValue() << " " << sensor->getSensorUnit() << endl;
    return 0;
}
--- Sensor Telemetry Abstraction --- Live Sensor Reading: 28.5 °C
10. Authentication Provider Abstraction (OAuth vs LDAP)
Abstracts user login validation protocols across OAuth2 and enterprise LDAP directories.
C++ / Authentication Provider Abstraction
#include 
#include 
#include 

using namespace std;

class AuthProvider {
public:
    virtual bool verifyCredentials(string username, string credential) = 0;
    virtual ~AuthProvider() {}
};

class LdapAuthProvider : public AuthProvider {
public:
    bool verifyCredentials(string username, string password) override {
        cout << "[LDAP Directory]: Validating enterprise user " << username << endl;
        return (password == "Enterprise@2026");
    }
};

int main() {
    cout << "--- Auth Provider Abstraction ---" << endl;
    unique_ptr auth = make_unique();
    bool status = auth->verifyCredentials("aarav.sharma", "Enterprise@2026");
    cout << "Authentication Result: " << (status ? "SUCCESS" : "FAILED") << endl;
    return 0;
}
--- Auth Provider Abstraction --- [LDAP Directory]: Validating enterprise user aarav.sharma Authentication Result: SUCCESS