Interfaces help us define a set of actions without saying how to do them. This lets different parts of a program work together smoothly.
Interface-like behavior in 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.
class Printable { public: virtual void print() = 0; // must be implemented 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; } };
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.
#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; }
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.
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.