Error: potentially uninitialized local variable

Hi. I have a function that spawns a gun from weapon class and returns spawned gun as its return type. and i can use the members of that spawned gun in code only before compiling and compiler gives me an error about return type.

this is spawngun function:

AWeapon* AHeroCharacter::SpawnGun()
{
	AWeapon* Weapon;
	if (WhatToSpawn)
	{
		UWorld* const World = ();
		if (World)
		{
			FActorSpawnParameters sp;
			sp.Owner = this;
			sp.Instigator = Instigator;
			FVector SpawnLocation = FVector(-80, -20, 0);
			FRotator SpawnRotation = GunTemp->GetComponentRotation();
			Weapon = World->SpawnActor<AWeapon>(WhatToSpawn, SpawnLocation, SpawnRotation, sp);

			Weapon->AttachRootComponentTo(GunTemp);
			
		}
	}
	return Weapon;
	
}

if i define return type as a reference and return dereferenced weapon gives me the same error.
i cannot understand where i did wrong.
in blue print tutorials i saw that the return type of a spawn function was promoted to a variable and the used somewhere else. I want do the same in my code.

Do I have to get all guns from weapon class at begin play and then cast them to weapon and then use them?
i want to use a object from weapon class in my character class

This error appers (which is really a warning, but UBT configuration warning level make it not tolerate) when you declere varable, but you first set it (init) in conditinal scope, which means it might be “potentially uninitialized” if “IFs” fails as error say. Weapon = nullptr; right after AWeapon* Weapon; or AWeapon* Weapon = nullptr; should fix it

2 Likes

thank you that worked. now i have another problem.
how can i use that returned gun in other functions in my character class?
the returned gun is in scope of begin play function.?

I mean how to promote that as a completely individual object of weapon class to use it wherever i want?

As any other functions like SpawnActor() :slight_smile: just call it like you would use any other varable, for example

AWeapon* CurrentWeapon = SpawnGun();

Ofcorse you need to prepare your code that this function may return null

I you dynamiclly allocate something in memory it will stay there forever until you destroy it or in case of UE4 garbage collector will remove it if it’s not refrenced by anything).

So when you call SpawnActor it creates actor in world and return pointer to it so you can control it, whatever you do to pointer does not effect object it self (or else you use “delete” operator on it which will destroy object in memoery, then it probably gonna crash UE4, whats why you should not use “new” or “delete” operators on UObject classes). if you lose pointer, you lose control of object, but you can get pointer back with other means. So when you spawn something keep it in varable, also use UPROPERTY() so varable is monitored by engine and GC will keep object in check

, your answers is amazing. It’s very helps to learn ue cpp. Thank you very much!