yogesh patel
yogesh patel

Reputation: 375

Interface in cpp

I want to create interface in cpp such that is any class implement that class then that class must implement parent class's functions. if all functions are not implemented then it must shows error.

class parent {   // interface class
   public :
      virtual void display();
}
class base : public parent {
    void display(); // this method must be implemented in this class 
}

please help me for this type of inheritance in c++.

Upvotes: 3

Views: 5231

Answers (3)

hurricane1026
hurricane1026

Reputation: 113

you can use abstract class(or pure virtual class):

class AB {
public:
    virtual void f() = 0;
};

abstract class can be used in cpp like interface in java/c#, although they were different in compiler's perspective.

Upvotes: 1

Riley Adams
Riley Adams

Reputation: 314

Use a pure virtual member function:

virtual void display() = 0;

This makes the class abstract (you can't make instances of it), and any non-abstract deriving class must implement such functions.

Here's a Wikipedia link with a more formal definition: http://en.wikipedia.org/wiki/Virtual_function#Abstract_classes_and_pure_virtual_functions

Upvotes: 10

john
john

Reputation: 88017

Just one change

class parent {   // interface class
   public :
      virtual void display() = 0;
}

This is called a pure virtual function in C++.

Upvotes: 8

Related Questions