Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Java interfaces in C++? [duplicate]

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.

like image 301
nickbrickmaster Avatar asked Aug 14 '12 04:08

nickbrickmaster


People also ask

Does C++ have interfaces like Java?

C++ does not provide the exact equivalent of Java interface : in C++, overriding a virtual function can only be done in a derived class of the class with the virtual function declaration, whereas in Java, the overrider for a method in an interface can be declared in a base class.

Can interfaces be subclassed?

No. An interface defines how a class should look like (as a bare minimum). Whether you implement this in a base class or in the lowest subclass doesn't matter.

CAN interface have multiple methods?

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. An interface can contain any number of methods.

What is the difference between interface and @interface in Java?

With @interface you're defining annotations, with interface you're defining interfaces. From Oracle docs: "Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program.


1 Answers

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.     } }; 
like image 152
StackedCrooked Avatar answered Sep 21 '22 21:09

StackedCrooked