I'm working on a C++/CX project and just came across the following definition:
#pragma once
struct ColorHelper abstract final {
static COLORREF Lighten(COLORREF color, int amount);
static COLORREF Darken(COLORREF color, int amount);
static bool IsSystemThemeDark();
};
I'm a bit confused. The abstract keyword tells me that I cannot instatiate this class but the final keyword says that I cannot derive from it, so what gives? Is this supposed to be like a namespace? Or maybe something like a static class in C#?
The abstract keyword tells me that I cannot instatiate this class but the final keyword says that I cannot derive from it, so what gives?
That's correct. The only available operation for this type is accessing its static
class members.
Is this supposed to be like a namespace?
Yes, pretty much. If ColorHelper
was a C++ namespace it would have an identical interface as far as clients are concerned.
So then, why is it not a namespace and rather a type with a somewhat obscure definition?
Because not all programming languages (such as C#) support calling free functions. Since ColorHelper
is a Windows Runtime type there are restrictions on how it can be modeled to support cross-language interoperability. Specifically, all functions need to be implemented on a type, even when that means introducing a type that can never be instantiated.
In essence, an abstract final
type with static
class members exclusively is the moral equivalent of a C++ namespace expressed in a way that makes it accessible across all supported Windows Runtime languages.