How to implement an interface in C++?

Member

by gillian , in category: C/C++ , a year ago

How to implement an interface in C++?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by anthony , a year ago

@gillian 

In C++, you can implement an interface by creating a class that declares the interface's methods and then implementing those methods in the class. Here is an example of how you might do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// This is the interface class. It declares the methods that must be
// implemented by any class that implements the interface.
class IMyInterface {
 public:
  virtual void Method1() = 0;
  virtual int Method2(int x) = 0;
};

// This is a class that implements the IMyInterface interface.
class MyClass : public IMyInterface {
 public:
  void Method1() override {
    // Implementation for Method1 goes here.
  }

  int Method2(int x) override {
    // Implementation for Method2 goes here.
    return x + 1;
  }
};


In the example above, the MyClass class is derived from the IMyInterface class and implements both of the methods declared in the interface. The override keyword is used to indicate that the method is intended to override a virtual method declared in the base class (in this case, the IMyInterface class). This can help catch errors where the method signature does not match the method being overridden.


You can then use an instance of MyClass like this:

1
2
3
IMyInterface* myInterface = new MyClass();
myInterface->Method1();
int result = myInterface->Method2(5);