Download

C++ inherit from 2 different classes?

Hello, this is more of a C++ question than an Unreal question, but I have no idea what to google for this.

Here’s my situation, I have an Npc (Towns people) and an NpcObject (Signs, inanimate objects you can talk to)
Npc inherits from Unit and Pawn, while the NpcObject inherits from Actor

Npc > Unit > Pawn
NpcObject > Actor

Both Npc and NpcObject have a ton of the same variables to allow the player to talk and interact with them.
But it’s a pain because when you interact with them, I need to have the same huge chunk of code written twice for each.
Ex:



AActor* actor = GetInteractedActor();

ANpc* npc = Cast<ANpc>(actor);
if(npc){
    npc->DoThis();
    //Lots of code here
}

ANpcObject* obj = Cast<ANpcObject>(actor);
if(obj){
    obj ->DoThis();
    //Lots of code here
}


Is there some way I can unify them so I only need to write the code once?
Maybe a way to ignore the class type somehow if they have the same properties?
Ex:



AActor* actor = GetInteractedActor();

actor->DoThis(); //Runs the function whether actor is an Npc or NpcObject
//Lots of code here


Any ideas would be greatly appreciated, thanks!

UE4 only can inherit from non-UObjects and from Interfaces.
I think interfaces are the way you want to go: https://wiki.unrealengine.com/Interfaces_in_C%2B%2B

Right there on the first line: “Interfaces allow different objects to share common functions”
Beautiful thanks!

Keep in mind, EMPTY functions.

Interfaces do not carry over any implementation details, they literally are only the “interface” aka the schematic of functions that must be present in the child class.

The implementation will not exist for said interface unless the child is also inheriting from a parent class in which said interface was already defined and implemented.

The other way to do it is often called component architecture. You make a class/struct that has the functionality you want, InteractingComponent and then give that to each of your Class types that wants to have that type of behavior.

UE4 has a Component system, you can do it literally that way, or you can just make it yourself and assign it to a variable in your classes that have it.