Say I have a C# interface called IMyInterface
defined as follows:
// C# code public interface IMyInterface { void Foo(string value); string MyProperty { get; } }
Assume I also have a C++/CLI class, MyConcreteClass
, that implements this interface and whose header is declared as follows:
// C++/CLI header file ref class MyConcreteClass : IMyInterface { public: };
How does one implement the method Foo
and the property MyProperty
in the C++/CLI header?
My attempt results in the following compile error:
error C3766: 'MyConcreteClass' must provide an implementation for the interface method 'void IMyInterface::Foo(System::String^ value)'
To declare an interface, use the interface keyword. It is used to provide total abstraction. That means all the methods in an interface are declared with an empty body and are public and all fields are public, static, and final by default.
Interfaces can declare that implementing types must define operators or other static members. This feature enables generic algorithms to specify number-like behavior.
The implements keyword is used to implement an interface . The interface keyword is used to declare a special type of class that only contains abstract methods. To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends ).
public ref class MyConcreteClass : public IMyInterface { public: virtual void __clrcall Foo(String^ value) sealed; virtual property String^ __clrcall MyProperty { String^ get() sealed { String::Empty; } } };
Interfaces need to be defined as virtual. Also note the "public IMy.." after the class decleration, it's a slighly different syntax than C#.
If you can, seal the interface members to improve performance, the compiler will be able to bind these methods more tightly than a typical virtual members.
Hope that helps ;)
I did not compile it but looks good to me... Oh and also, defining your methods as __clrcall eliminates dangers of double thunk performance penalties.
edit the correct syntax for a property is:
public ref class MyConcreteClass : public IMyInterface { public: virtual property String^ MyProperty { String^ get() sealed { return String::Empty; }; void set( String^ s ) sealed { }; } };
or, when putting the definition in the source file:
public ref class MyConcreteClass : public IMyInterface { public: virtual property String^ MyProperty { String^ get() sealed; void set( String^ s ) sealed; } }; String^ MyConcreteClass::MyProperty::get() { return String::Empty; } void MyConcreteClass::MyProperty::set( String^ ) { //... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With