Skip to main content

Object oriented programming

[C++] OOPs - Interfaces

Declaring an Interface in C++ (and the Magic of Abstraction)

Let’s Begin: Why Hide the Details?

Imagine you walk into a coffee shop.
You say, "One cappuccino, please."
The barista smiles, taps some buttons on a fancy machine, and voilà! your coffee appears.

Now, think about this: Did you need to know how the machine works inside?
Did you need to understand water temperatures, pressure valves, bean grinding, milk frothing?

No! You just used the coffee shop’s interface: you ordered, you received.


This is the first big idea we need to feel before diving into code:
👉 An interface is a way to use something without knowing how it works inside.

It hides the messy complicated details and gives you only what you need.

This hiding of inner complexity is called abstraction.


Abstraction: Your Secret Superpower

Let’s slow down even more.

Have you ever driven a car? Or played a video game?

  • In a car, you press the gas pedal → the car goes faster.
  • In a video game, you press "jump" → the character leaps.

You don't think:
"Hmm, when I press the gas, fuel injectors spray fuel into the cylinders at high pressure..."

No! You abstract all that crazy detail into a simple action.

In programming, abstraction lets us hide the complicated parts of code and show only the important actions.

Summary so far:

ConceptReal-Life ExampleProgramming View
InterfaceCoffee shop counter, car pedalsSet of simple actions
AbstractionHiding machine internalsHiding code complexity

Enter: Abstract Classes in C++

Alright, you're getting the feeling of it.
Now, how does C++ let us build these "simple action doors" for others to use?

One very important tool: abstract classes.

But first... what’s a regular class?

Quick reminder:
A class is like a blueprint for making objects.

class Dog {
public:
    void bark() {
        std::cout << "Woof!" << std::endl;
    }
};

Here, Dog is a class. You can make dogs, and they can bark.

Simple, right?


Now, the twist: What if you don't know how the dog will bark yet?

What if you want to say:
"Every animal must have a speak function, but I don’t care how they do it. Each animal will decide."

You just want to set a rule, not the actual behavior.

This is where abstract classes come in.

In C++, an abstract class is a class that has at least one pure virtual function.

What’s a pure virtual function?

It's a function that says:
"Hey, I exist, but I don’t know how to do my job yet. Someone else must implement me later."

You declare it like this:

virtual void speak() = 0;

Notice the = 0; at the end.
That’s how C++ knows: this is a pure virtual function.


Full Example: Abstract Animal

class Animal {
public:
    virtual void speak() = 0;  // pure virtual function
};

This Animal class is now abstract because it has a pure virtual function.

You cannot create an Animal object directly, like:

Animal a;  // ❌ Error! Cannot instantiate an abstract class

You must create a subclass that implements speak().


"Building a Universal Remote"

  • Set up a relatable situation: Imagine if every new device (TV, speaker, game console) needed its own secret handshake to turn on.

Connect this universal remote idea to interfaces in C++:

"Interfaces are like universal remotes for your code — they define what must exist without caring how it’s built."

Question to the reader:

“Wouldn’t it be easier if every device just agreed to follow the same buttons: Power, Volume, Channel?”

The Problem Without Interfaces

  • What happens when every class invents its own methods?
  • Real-world analogy: Different plugs and chargers in every country.
  • Tiny C++ Example: two classes Dog and Cat with random, uncoordinated function names (bark(), meow()).

Key Question:

"If you want to treat all animals the same... how can you call a function if you don't even know what it's named?"

What Exactly Is an Interface?

  • Plain English first: A promise, not a blueprint.
  • Then, the C++ terms:
    • Abstract class
    • Pure virtual function
  • Table of Terms and Definitions (Simple & Friendly)

First "Wow" Moment:

"You can’t create an abstract class... because it’s not a full recipe yet!"

Mini Code Example: Basic Animal class with a pure virtual function speak().


Step-by-Step — How Interfaces Work in C++

  • Defining a pure virtual function
  • Overriding in subclasses
  • Why you use override ?
  • How C++ enforces the rules at compile time (prevents missing functions)

Code Example:

  • Animal → Dog and Cat

Real World Tie-In:

"Just like every remote needs a Power button, every animal must know how to speak, but they get to choose what sounds they make."

Interface vs Abstract Class — Wait, Aren’t They the Same?

  • In C++, "interface" is usually just an abstract class with only pure virtual functions
  • Table comparing Interface vs Abstract Class.

Real-world analogy:

"Interface = contract. Abstract class = contract + maybe some helpful starter tools."

Gotcha:

"C++ doesn’t have a special interface keyword like Java. It’s all about how you design the class."

Why Use Interfaces? (The Deep Reasons)

  • Enforces Consistency: Everyone must follow the same "remote control."
  • Decouples Code: Swap out new animals/devices without breaking everything else.
  • Scales Easily: Big projects need solid rules.
  • Mocks and Testing: How interfaces make unit testing cleaner.

Real-World Story:

"Imagine trying to change the batteries in a remote that doesn't open the same way twice. Nightmare."

Common Pitfalls (and How to Dodge Them)

  • Forgetting to mark functions override
  • Accidentally making classes non-abstract by missing the = 0
  • Diamond Problem when mixing multiple interfaces
  • Relying too much on inheritance (prefer composition sometimes!)

Mini Quiz / Self-Check:

  • "Spot the Bug" mini examples to fix.

Interfaces in Action — Building a Small System

Subsections:

  • Design a tiny app: Animal Shelter
    • Interface: Animal
    • Subclasses: Dog, Cat, Bird
    • Manager class that handles Animal* pointers without caring which animal
  • Show clean extensibility: add Fish later without changing manager code.

Implementing the Interface

Let's make two animals:

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

class Cat : public Animal {
public:
    void speak() override {
        std::cout << "Meow!" << std::endl;
    }
};

Now, we can use Dog and Cat freely:

Dog d;
d.speak();  // Output: Woof!

Cat c;
c.speak();  // Output: Meow!

Each subclass (Dog, Cat) has its own version of speak().

The abstract class (Animal) simply defined the rule: "every animal must speak,"
but left the how up to each child class.


Final Summary — Your Mental Model of Interfaces

  • Quick recap of key ideas
  • Reconnect to the Universal Remote analogy

Closing thought:

"Interfaces let you focus on what matters: pressing Play, not reading a 300-page manual every time you want to watch TV."

Bonus: Quick Reference Cheatsheet

  • What makes an abstract class?
  • How to define an interface
  • When to use interface vs abstract class
  • 3 Common gotchas to avoid

Notes:

  • Every section should feel like you’re talking directly to the reader, with a casual mentor tone: "Here’s what’s weird…", "Watch out here…", "This part’s magic once you see it..."
  • Smart use of tables and tiny code snippets to break down tricky points
  • Keep questions flowing: "Why would you do this?" / "What happens if you forget this?" / "How is this better?"