4

As per the MSDN doc on __interface, a Visual C++ interface "Cannot contain constructors, destructors, or operators."

Why can't an interface contain an operator? Is there that much of a difference between a get method that returns a reference:

SomeType& Get(WORD wIndex);

and the overloaded indexer operator?

SomeType& operator[](WORD wIndex);

3 Answers 3

8

The __interface modifier is a Visual C++ extension to help implementing COM interfaces. This allows you to specify a COM 'interface' and enforces the COM interface rules.

And because COM is a C compatible definition, you cannot have operators, Ctor or Dtors.

2
  • So, if I want to have an "interface" with operators, is my only choice a pure virtual class?
    – iano
    Jan 8, 2010 at 21:03
  • 1
    Your "only choice" is to write a standard C++ class, yes. There are plenty of approaches depending on what you need. A pure abstract class is the closest you're going to get to Java/C# type interfaces, but in many cases, a better solution in C++ is to not define an interface. Use the duck-typing provided by templates, and simply define the concepts a class must support, and don't bother requiring it to derive anything. Or use the CRTP idiom to provide an interface for static polymorphism.
    – jalf
    Jan 8, 2010 at 23:05
1

This looks like a .dll thing. You need a method name so you can use it other languages that don't support operator overloading, eg C.

1

Interfaces cannot contain operators because operators cannot be virtual functions. Essentially interfaces are base classes that other classes derive from.

Edit: After reading the comments and thinking about this more I realized how stupid this was. Please forgive my eager fingers. Operators are no different than any other function. A more likely reason has to do with __interface generating classes which derive from a common base class, and the necessity for dlls to have all constructors, destructors, and assignment operators that they use locally.

2
  • Operators can be virtual, related question: stackoverflow.com/questions/669818/…
    – sbk
    Jan 8, 2010 at 18:28
  • Operators can be virtual in standard C++. A lot of them shouldn't be, because for instance operator= should take a reference of the same type as parameter, and you can get into all sorts of trouble trying to do polymorphic assignment. But operator[] is a reasonable candidate for polymorphism. Admittedly the non-virtual interface idiom is often preferable in pure C++, but that's true of non-operator functions too. Jan 8, 2010 at 18:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.