I noticed that there are sealed and interface keywords in C++. Is this just for CLR C++? If not, when were sealed and interface added to the C++ standard? Do they have the same meaning in C++ as they do in C#? If not, how do I get the equivalent in standard C++?
sealed
and interface
keywords are only for C++/CLI. See Language Features for Targeting the CLR for more details.
In standard C++ interface
could be replaced with pure virtual class and multiple inheritance. Sealed
keyword could be replaced with boost::noninheritable
(which is not an official part of boost yet).
An interface
can be duplicated in C++ with a pure virtual class, taking advantage of the fact that you can do multiple inheritance.
sealed
can be winged with a private constructor and a sort of factory pattern (to actually obtain instances of the sealed class). There's a couple other examples at the C++ FAQ Lite.
__interface
is valid in Visual C++ as of VS 2005. It provides additional compile-time validation that the interface looks and smells like one should. (The linked MSDN article has the full details.)
__sealed
, however, appears only to be part of the "Managed Extensions for C++."
interface
and sealed
were added by MS for the C++/CLI implementation. However, current versions of the Microsoft compiler do support the sealed
keyword for native code, too - but that's an extention that you'll likely never find elsewhere.
Note that MS has done something similar with override
- it's a keyword extension in MSVC that indicates a function is intended to override a base class virtual function (the compiler will complain if that turns out not to be the case).
For some reason, Microsoft didn't do the same for the interface
keyword, but they do have the __interface
keyword extension that does what you might expect. I suspect that they didn't add a native interface
keyword extension because the interface
identifier is found in a lot of existing code (maybe as a macro that resolves to class
) - but that's just a guess on my part.
Another factor for why __interface
has the underscores while sealed
and override
doesn't might be because the latter are "context-sensitive keywords" - a technology that MS introduced in C++/CLI that makes some identifiers keywords only in certain grammar contexts - so sealed
and override
can still be used as variable or function names, even if they're also used as the keywords. The compiler can determine from the context which use is appropriate. Maybe they couldn't get away with that for interface
.
Anyway you can maybe get the best of both worlds with something like:
#if _MSC_VER >= 1400
#define OVERRIDE override
#define SEALED sealed
#define INTERFACE __interface
#else
#define OVERRIDE
#define SEALED
#define INTERFACE class
#endif
which I blatently stole from: