0
0
C++programming~5 mins

Interface-like behavior in C++

Choose your learning style9 modes available
Introduction

Interfaces help us define a set of actions without saying how to do them. This lets different parts of a program work together smoothly.

When you want different classes to share the same actions but do them differently.
When you want to make sure certain functions exist in many classes.
When you want to write code that works with many types of objects in the same way.
When you want to separate what something does from how it does it.
Syntax
C++
class InterfaceName {
public:
    virtual void action() = 0; // pure virtual function
    virtual ~InterfaceName() = default; // virtual destructor
};

A pure virtual function (= 0) means the class is abstract and cannot be instantiated directly.

Derived classes must provide their own version of the pure virtual functions.

Examples
This defines an interface named Printable with one action: print.
C++
class Printable {
public:
    virtual void print() = 0; // must be implemented
    virtual ~Printable() = default;
};
Document class implements the Printable interface by defining print.
C++
class Document : public Printable {
public:
    void print() override {
        std::cout << "Printing document..." << std::endl;
    }
};
Image class also implements Printable but prints differently.
C++
class Image : public Printable {
public:
    void print() override {
        std::cout << "Printing image..." << std::endl;
    }
};
Sample Program

This program shows interface-like behavior. Printable is an interface with print(). Document and Image implement print() differently. The function printAnything() can print any Printable object.

C++
#include <iostream>

class Printable {
public:
    virtual void print() = 0;
    virtual ~Printable() = default;
};

class Document : public Printable {
public:
    void print() override {
        std::cout << "Printing document..." << std::endl;
    }
};

class Image : public Printable {
public:
    void print() override {
        std::cout << "Printing image..." << std::endl;
    }
};

void printAnything(Printable& item) {
    item.print();
}

int main() {
    Document doc;
    Image img;

    printAnything(doc);
    printAnything(img);

    return 0;
}
OutputSuccess
Important Notes

Interfaces in C++ are made using classes with only pure virtual functions.

Always provide a virtual destructor in interfaces to avoid memory issues.

You cannot create objects directly from an interface class.

Summary

Interfaces define what actions a class must have without saying how.

Use pure virtual functions (= 0) to create interfaces in C++.

Classes that inherit interfaces must implement all pure virtual functions.