views:

243

answers:

3

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);
+1  A: 

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.

eduffy
+1  A: 

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.

Chris
Operators **can** be virtual, related question: http://stackoverflow.com/questions/669818/virtual-assignment-operator-c
sbk
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.
Steve Jessop
+7  A: 

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.

Christopher
So, if I want to have an "interface" with operators, is my only choice a pure virtual class?
Ian
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