Implementing a UInterface on an object

Ensure that you've followed the previous recipe in order to have a UInterface ready to be implemented.

How to do it...

  1. Create a new Actor class using the Unreal Wizard, called SingleInterfaceActor.
  2. Add IInterface—in this case, IMyInterface—to the public inheritance list for our new Actor class:
    class UE4COOKBOOK_API ASingleInterfaceActor : public AActor, public IMyInterface
  3. Add an override declaration to the class for the IInterface function(s) that we wish to override:
    FStringGetTestName() override;
  4. Implement the overridden function in the implementation file by adding the following code:
    FStringASingleInterfaceActor::GetTestName()
    {
      return IMyInterface::GetTestName();
    }

How it works...

  1. C++ uses multiple inheritance for the way it implements interfaces, so we leverage that mechanism here with the declaration of our SingleInterfaceActor class, where we add public IMyInterface.
  2. We inherit from IInterface rather than UInterface to prevent SingleInterfaceActor from inheriting two copies of UObject.
  3. Given that the interface declares a virtual function, we need to redeclare that function with the override specifier if we wish to implement it ourselves.
  4. In our implementation file, we implement our overridden virtual function.
  5. Inside our function override, for demonstration purposes, we call the base IInterface implementation of the function. Alternatively, we could write our own implementation, and avoid calling the base class one altogether.
  6. We use IInterface:: specifier rather than Super, because Super refers to the UClass that is the parent of our class, and IInterfaces aren't UClasses (hence, no U prefix).
  7. You can implement a second, or multiple, IInterfaces on your object, as needed.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.104.214