Introduction

As we conclude this course and the entire course path, let's add one more tool to our tool belt. Since we covered the wrap method in a previous lesson, it only makes sense to discuss the wrap class technique, which allows us to expand the behavior of an entire class without altering its original implementation. This approach is particularly useful when we need to add new functionality to a class while preserving its existing behavior, ensuring that the original class remains unchanged and reliable.

Understanding the Wrap Class Technique

The wrap class technique in C++ involves creating a new class that encapsulates an existing class to extend its functionality. In C++, we often use inheritance or composition to achieve this. By using these techniques, the new class can intercept and augment the behavior of the original class's methods. This technique is beneficial when we want to add new features without modifying the original class, thus maintaining its integrity and reducing the risk of introducing bugs.

Implementing Wrap Class

To implement a wrap class in C++, we can use composition to encapsulate the original class within a new class. This allows the new class to extend the functionality of the original class. Let's look at a practical example:

class OrderProcessor {
public:
    virtual bool ProcessOrder(const Order& order) {
        // Original processing logic
        return true;
    }
    
    virtual bool CancelOrder(const Order& order) {
        // Original cancellation logic
        return true;
    }
};

class LoggingOrderProcessor : public OrderProcessor {
private:
    OrderProcessor& _orderProcessor;
    ILogger& _logger;
    
public:
    LoggingOrderProcessor(OrderProcessor& orderProcessor, ILogger& logger)
        : _orderProcessor(orderProcessor), _logger(logger) {}

    bool ProcessOrder(const Order& order) override {
        _logger.Log("Processing order...");
        bool result = _orderProcessor.ProcessOrder(order);
        _logger.Log("Order processed.");
        return result;
    }
    
    bool CancelOrder(const Order& order) override {
        _logger.Log("Cancelling order...");
        bool result = _orderProcessor.CancelOrder(order);
        _logger.Log("Order cancelled.");
        return result;
    }
};

In this example, LoggingOrderProcessor wraps OrderProcessor, adding new functionality to both ProcessOrder and CancelOrder methods. This allows us to extend the behavior of OrderProcessor without modifying its original code.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal