How do I call a static function without any instance of the class

I have a projectile class called
BaseProjectile.h

Inside the projectile class, I have a static function called

static void OnFire();

What the static function does is it spawns an instance of the class baseprojectile.

I want to call this function through another class class but unable to do it.

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay)
	TSubclassOf<class ABaseProjectile> CurrentProjectile;

In the c.pp file, I can call it by

CurrentProjectile::OnFire or any other means like → or :

How call I call the static function?

Static functions can be called from outside their class via the ClassName::FunctionName() syntax, eg, ABaseProjectile::OnFire().

If I have a

TSubclassOf CurrentProjectile;

And the class whose static function I want to call is stored in the variable CurrentProjectile. Can I call that static function through the variable CurrentProjectile?

You can, but static functions aren’t bound to a particular instance, so it behaves no different than calling it with the type.

These do exactly the same thing:

FFoo f;
f.Static();
FFoo::Static();

If I have a

 TSubclassOf<class ABaseProjectile> CurrentProjectile;

and ABaseProjectile has a static function called fire.

How do I call that static function using the variable CurrentProjectile? I don’t have any instance of it before calling the function.

You should be able to just do CurrentProjectile::OnFire(), since you are declaring that to be a subclass. Does this not work? Static functions are not called on instances, they are called from the class itself.

Just do ABaseProjectile::OnFire();

The function is static. It doesn’t use a this pointer, so you don’t need to call it on an instance.

Sadly it is not working…

12562-untitled.jpg

Is there any other work around for this?

But my variable ( TSubclassOf CurrentProjectile) stores a blueprint class rather than the c++ class. I want to call the static function of that blueprint class.

I could find a work around for it lets see.

I see… that’s not how statics work, as they have no runtime polymorphic behaviour.

It looks like you’re trying to make a factory for projectiles of a certain type?

Rather than have a static function on your projectile classes, why not spawn a projectile of type CurrentProjectile and then call a virtual function on it to set it up appropriately?

If you take a look, our AI tests do something similar with pawns (UE4/Engine/Source/Developer/FunctionalTesting/Classes/FunctionalAITest.h).

FAITestSpawnInfo has a variable called PawnClass, which is used with UWorld::SpawnActor to spawn an object of the correct type. This sounds similar to what you’re trying to achieve with your projectiles, eg).

ABaseProjectile* NewProjectile = World->SpawnActor<ABaseProjectile>(*CurrentProjectile);
NewProjectile->SomeVirtualFunctionToConfigureTheInstance();

Did you realize you misspelled your class name?

1 Like