As you know, separate language tools for declaring interfaces in C ++, and their role can be performed by abstract classes. But from an ideological point of view, interfaces and abstract classes are quite different entities. Interfaces describe a contract of how to interact with a class. Abstract classes are the root of the class hierarchy, used for polymorphism in the spirit of

AbstractSuperClass* a = new SubClass; 

and can simply implement common functionality.

Is it necessary, programming in C ++, to separate these concepts and write interfaces, as in Java / C #? Or you can (need?) Mix and use only abstract classes?

  • one
    But in C ++, as far as I remember, there are no interfaces, so you have to emulate them anyway with abstract classes, don't you? What do you mean by "divide"? - VladD
  • @VladD, just emulate. Those. use a separate abract class for “description of contracts” (interface), and a separate class for class hierarchy and polymorphism (the abstract class itself). Does it really make sense? Or in the pros do not do that? - NikBond
  • And, I understood the question. Well, I would divide, yes, in order to separate the logic of the contract from the logic of implementation. But I don't write in C ++, so let's wait for what the gurus say. - VladD

1 answer 1

In C # / Java, there is no multiple class inheritance, but there is multiple interface inheritance. Therefore, in these languages, the separation of interfaces and abstract classes has to be willy-nilly.

In C ++, there is no such restriction, therefore there is no particular need to single out a separate concept "interface" and separate it from the abstract class. The interface can be any abstract class, it does not even have to have public virtual functions (well, except for the destructor, if you need a polymorphic deletion). An example of such an interface is the NVI pattern.

If you wish to more closely match OOP to the C # / Java language paradigm, you can give the interface classes names starting with the letter I , or even add

 #define interface struct 

to distinguish the interface class when declaring / defining. Such approaches are used in MS COM.

But in general, this is not required, and the problem of the diamond-shaped hierarchy can be solved through virtual inheritance.