O – Open/Closed Principle (OCP) | Master CPP Design Patterns 2025

The Open/Closed Principle (OCP) is a golden rule of clean software design that says:

“Software entities should be open for extension but closed for modification.”

This means once your class or module is working correctly, you shouldn’t need to change its core logic when requirements evolve—you should extend it instead.

In this tutorial, we’ll explore how C++ developers can apply OCP using abstraction, inheritance, and polymorphism. You’ll learn how to write classes that adapt to new behavior without breaking or modifying existing code, making your software more maintainable, scalable, and bug-resistant.

What you’ll learn:

  • Real-world scenarios where OCP saves your codebase
  • How to refactor tightly coupled classes into OCP-compliant ones
  • OCP in action using abstract base classes and virtual functions
  • Clean, modern C++ examples explained line-by-line

Perfect for senior engineers and beginners looking to strengthen their design pattern foundation in 2025-ready C++ code!

What is OCP?

Definition:

Software entities (like classes, modules, functions) should be open for extension, but closed for modification.

What does that mean in simple terms?

  • Open for extension ➜ You should be able to add new features or behaviors to a class/module.
  • Closed for modification ➜ You should not change the existing code of that class/module when adding new features.

Why does this matter?

Imagine you’ve released a class into production. If you keep modifying it every time there’s a new requirement:

  • You might introduce bugs in already tested code.
  • You’ll have to retest the whole thing.
  • It becomes hard to maintain and scale.

Instead, we use abstraction (like interfaces or base classes) so we can extend behavior by adding new code, not changing existing code.

Real-World Analogy

Say you have a power socket.
Initially, it only supports a fan. Now you want to plug in a charger, light, or heater.

Bad approach:
Open the wall and change the wiring every time to support new devices.

Good approach:
Use standard sockets and plugs. You don’t change the wall — just plug in a new device.

That’s the Open/Closed Principle in action.

Example in C++: Without OCP ❌

class Invoice {
public:
    string type;

    double calculateTotal() {
        if (type == "Standard") {
            return 100.0;
        } else if (type == "Premium") {
            return 200.0;
        } else {
            return 0.0;
        }
    }
};

Problem:

  • Every time you want a new invoice type (like “Gold”, “Student”, etc.), you must modify this class.
  • You’re violating OCP because you’re not closed for modification.

Better Design With OCP

We use polymorphism (base class + derived classes):

class Invoice {
public:
    virtual double calculateTotal() = 0; // abstract method
};

Now, create new types without modifying the original class:

class StandardInvoice : public Invoice {
public:
    double calculateTotal() override {
        return 100.0;
    }
};

class PremiumInvoice : public Invoice {
public:
    double calculateTotal() override {
        return 200.0;
    }
};

Now you can extend it:

class StudentInvoice : public Invoice {
public:
    double calculateTotal() override {
        return 50.0;
    }
};

Your existing code doesn’t change, only new classes are added.

Testing the Principle

void printInvoiceTotal(Invoice* inv) {
    cout << "Total: " << inv->calculateTotal() << endl;
}

This function works for all invoice types — standard, premium, student — without changing anything.

Benefits of Following OCP

✅ Add new features without breaking existing ones
✅ Prevent bugs in well-tested code
✅ Easier collaboration in teams
✅ Better suited for large, evolving projects

Signs You’re Violating OCP

  • You see a lot of if, switch, or case checking types or conditions.
  • You modify the same class frequently for different behaviors.

Key Tools to Implement OCP in C++

  • Abstract Base Classes (interfaces) ➜ Define a contract
  • Virtual Functions ➜ Allow extension through overriding
  • Polymorphism ➜ Treat derived classes uniformly
  • Design Patterns like Strategy or Factory ➜ Naturally follow OCP

Summary

FeatureGoodBad
Add new types➕ Add a new class❌ Edit existing code
Follows OCP
Code safetySafe and extendableRisky and fragile

Want Hands-On Practice?

I can help you:

  • Build a shape area calculator using OCP
  • Implement a payment system that handles different methods (like card, UPI, wallet) using OCP
  • Understand where and when to use virtual functions and interfaces

Top Interview Questions on Open/Closed Principle (OCP) C++ Focused

  1. What is the Open/Closed Principle, and how is it applied in C++?
  2. Can you explain the benefits of using the Open/Closed Principle in real-world C++ projects?
  3. How does the Open/Closed Principle improve code maintainability and scalability in C++ applications?
  4. What design patterns in C++ support the Open/Closed Principle?
  5. Give a C++ code example that violates the Open/Closed Principle and explain how to refactor it.
  6. How do abstract classes and virtual functions help implement the Open/Closed Principle in C++?
  7. Can the Open/Closed Principle be misused? What are the trade-offs in C++ design?
  8. Describe a time in your project where applying the Open/Closed Principle in C++ saved you from introducing bugs.
  9. What is the relationship between the Open/Closed Principle and the Liskov Substitution Principle in C++?
  10. How do you ensure that your C++ class hierarchy adheres to the Open/Closed Principle during software evolution?
  11. What role do interfaces or pure virtual classes play in implementing the Open/Closed Principle in C++?
  12. How does the use of templates in C++ affect adherence to the Open/Closed Principle?
  13. Why is the Open/Closed Principle considered a core SOLID principle in modern C++ software architecture?
  14. Can you demonstrate how to use the Strategy pattern in C++ to follow the Open/Closed Principle?
  15. How do plugins or dynamic loading in C++ systems relate to the Open/Closed Principle?

Frequently Asked Questions (FAQ) – Open/Closed Principle (OCP)

1. What is the Open/Closed Principle in C++?

The Open/Closed Principle is one of the SOLID principles of object-oriented design. It states that a class, module, or function should be open for extension but closed for modification. This means you can add new features or behaviors without altering existing code, which helps in preventing bugs and promoting reusability.

2. Why is the Open/Closed Principle important in software design?

The Open/Closed Principle helps maintain stability in your codebase. By avoiding modifications to tested code and instead extending behavior, your system becomes more resilient to changes, easier to maintain, and better prepared for future enhancements.

3. How do I implement the Open/Closed Principle in C++?

You can implement the Open/Closed Principle in C++ using:

  • Abstract base classes or interfaces
  • Virtual functions and inheritance
  • Strategy or Decorator design patterns
    This allows new functionality to be introduced via subclasses without changing existing logic.

4. What is a real-life example of the Open/Closed Principle?

Imagine you have a PaymentProcessor class that handles payments. Instead of modifying it every time a new payment method (like UPI or crypto) is added, you create new subclasses like UPIPayment or CryptoPayment that extend the base PaymentProcessor. This follows the Open/Closed Principle by adding functionality without touching old code.

5. Does following the Open/Closed Principle increase code complexity?

Initially, applying the Open/Closed Principle may introduce abstraction layers that seem complex. However, in large-scale or growing systems, it pays off by making code more flexible, testable, and modular in the long run.

6. What are the common mistakes while applying the Open/Closed Principle?

Some developers over-engineer by applying the Open/Closed Principle too early or unnecessarily. It’s best to apply it when a class is likely to change in the future, not for every trivial use case. Premature abstraction can lead to harder-to-understand code.

You can also Visit other tutorials of Embedded Prep 

Special thanks to @mr-raj for contributing to this article on Embedded Prep

Leave a Reply

Your email address will not be published. Required fields are marked *