Talk:Inheritance and Interfaces

From RAD Studio
Jump to: navigation, search

Starting with C++Builder XE it's much easier to use the TCppInterfacedObject template rather than raw TInterfacedObject. TCppInterfacedObject takes care of the IUnknown methods so you don't have to provide dummy implementations of QueryInterface/AddRef/Release that delegate to TInterfacedObject. For example

#include <System.hpp>
#include <assert.h>

__interface __declspec(uuid("{AF75C8E8-0DF8-4B64-BBEE-34CA7A87521B}")) IMyInterface : IInterface
{
    virtual void setProp(int val) = 0;
    virtual int getProp() = 0;
    __property int Prop = { read=getProp, write=setProp };
};
typedef DelphiInterface<IMyInterface> _di_IMyInterface;


class TMyInterface : public TCppInterfacedObject<IMyInterface>
{
    int FVal;
public:
    void setProp(int val) { FVal = val; }
    int getProp() { return FVal; }
};

void test()
{
  _di_IMyInterface intf(static_cast<IMyInterface*>(new TMyInterface()));
  int val = 0x9897;
  intf->setProp(val);
  assert(intf->getProp() == val);
  assert(intf->Prop == val);
}

int main()
{
  test();
  return 0;
}