syntagma
syntagma

Reputation: 24344

What is a difference between a C++ concept and an interface?

My understanding is that C++ library concept is to C++ what interfaces like Closeable are to Java (as per the linked source, concepts are: named set of requirements).

  1. Is that analogy correct?
  2. What are the differences between C++ interface (i.e. class with pure virtual methods) and a C++ library concept?
  3. In general, is implementation of C++ library concepts through multiple inheritance equivalent of implementing multiple interfaces in Java (which does not have multiple inheritance)?

Upvotes: 4

Views: 871

Answers (2)

eerorika
eerorika

Reputation: 238421

  1. It's not an exact analogy, but concepts are similar to interfaces. A class with only pure virtual member functions is a closer analogy to Java interfaces. Java generics is perhaps a closer analogy to C++ concepts, but they are much more limited. You can only use them to require a type to inherit a particular base class or interface (I may be wrong). Haskell type classes are a quite close analogy to C++ concepts.

  2. A C++ interface is a class. Implementing an interface means inheriting the interface and implementing the pure virtual member functions. A concept is a set of requirements. Conforming to a concept means that the conforming class complies to all requirements. There can be requirements for validity of particular expressions (must have a member type alias named iterator) or for the behaviour (i++ must be equivalent to It ip=i; ++i; return ip;).

    Inheritance of interfaces can and must be defined in the language, but there is no language support for formally specifying concepts yet. Language support has been proposed, but not included in the current (C++14) standard.

    Inheritance is dynamic (runtime) polymorphism, while concepts are used in conjunction with templates, which is static (compile time) polymorphism.

  3. Not equivalent. Dynamic and static polymorphism are quite different things.

Upvotes: 2

Alexis Le Provost
Alexis Le Provost

Reputation: 2073

  1. No, it's wrong. Interfaces in Java as same as interfaces in C++ (a class where every method is virtual pure).

  2. C++ concept infers class functionnalities instead of C++ interface defines class functionnalities.

  3. C++ concepts have nothing to deal with inheritance. Concept determines what a class can do and not how a class should be implementing.

Upvotes: 0

Related Questions