Equivalent of Java interfaces in C++?

nickbrickmaster picture nickbrickmaster · Aug 14, 2012 · Viewed 22.8k times · Source

Possible Duplicate:
How do you declare an interface in C++?
Interface as in java in c++?

I am a Java programmer learning C++, and I was wondering if there is something like Java interfaces in C++, i.e. classes that another class can implement/extend more than one of. Thanks. p.s. New here so tell me if I did anything wrong.

Answer

StackedCrooked picture StackedCrooked · Aug 14, 2012

In C++ a class containing only pure virtual methods denotes an interface.

Example:

// Define the Serializable interface.
class Serializable {
     // virtual destructor is required if the object may
     // be deleted through a pointer to Serializable
    virtual ~Serializable() {}

    virtual std::string serialize() const = 0;
};

// Implements the Serializable interface
class MyClass : public MyBaseClass, public virtual Serializable {
    virtual std::string serialize() const { 
        // Implementation goes here.
    }
};