TakeDamage

In the gun class, we write

OutHit.GetActor()->TakeDamage(DamageAmount, DamageEvent, OwnerController, this);

Whereas in the Shooter Character we write:

float DamageApplied = Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser) which is called on a pawn.

My question is how does Unreal know to cll the TakeDamage() function in our Shooter Character class when we call it on the getactor()? I’ve been struggling with this for a while and wanted to clear it. I think it’s more than just virtual function and so. It would’ve made sense if we got the ShooterCharacter object but it’s through the actor and from what I know so far, base classes can’t call funcitons of child classes.

Does it have to do with events and delegates?

Okay, I asked ChatGPT which mentioned polymorphism and virtual functions which didn’t help since we’re calling the function on a child class and then calling the Super::TakeDamage which refers to the base class in the parent which is pawn.

It also mentioned dynamic dispatch which determines which implementation of a polymorphic operation to call at runtime. I think this is advanced but wanted to ask if you could clear it. I think this is deeper.

I think you might be conflating two things as Super::TakeDamage isn’t related to what’s going on. So lets start with

Because that’s what virtual functions do. They will call the most derived version of the function for the actual object being pointed/referenced. You hit an AShooterCharacter so it will call AShooterCharacter::TakeDamage

Demonstration: Compiler Explorer

In generic terms virtual functions is how C++ implements “dynamic dispatch”.


Super is just a type alias for the parent class. i.e. it’s

using Super = ACharacter;

example:

struct Foo
{
    int Num() 
    { 
        return 5; 
    }
};

struct Bar : Foo()
{
    int Num() 
    { 
        return Foo::Num(); // calls function defined above, returns 5
    };
};

without fully qualifying the call to Foo::Num within Bar::Num you would have an infinite recursive function. That’s all you’re really doing there, disambiguating.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms