Interfaces in C++

Overview

Interfaces allow you to declare expected features (methods) for classes without implementing them. In Java there is a special language feature for this, in C++ you can use abstract classes. Also, in Windows, interfaces are part of COM/DCOM functionality (language-independent concept, see __interface).

Basic example

The simplest method for implementing interfaces in C++ is to use abstract classes like the following:

class NamedIntf 
{
public:
  /// returns object name
  virtual string getName() = 0;
  // required for memory leak protection
  virtual ~NamedIntf() { }
};

class ProductIntf
{
public:
  /// returns price in base currency
  virtual int getPrice() = 0;
  // required for memory leak protection
  virtual ~ProductIntf() { }
};

class Car: public ProductIntf, public NamedIntf {
  virtual int getPrice() { return 20000; }
  virtual string getName() { return "A car"; }
};

class Dog: public NamedIntf {
  virtual string getName() { return "A dog"; }
};

void showObjectName(const NamedIntf &named) {
  cout << "Object name = [" << named.getName() << "]" << endl; 
}

Car car;
Dog dog;

showObjectName(car);
showObjectName(dog);

How to check if object implements a given interface?

You can use dynamic_cast or wrapper for it:

template < class TypeTo, class TypeFrom >
TypeTo *interface_cast(TypeFrom *t) {
    TypeTo *res = dynamic_cast<TypeTo *>(t);
    return res;
}

template < class TypeTo, class TypeFrom >
bool implements_interface(TypeFrom *t) {
  return (interface_cast<TypeTo>(t) != nullptr);
}

unique_ptr<Dog> dog(new Dog());
cout << "your dog has name? " << (implements_interface<NamedIntf>(dog.get())?"yes":"no") << endl;

Tutorials

Other solutions

See also

Share

follow