At 11:28 in the lecture he makes
const FHitResult getFirstPhysicsBodyInReach();
What he the reason for this function being a const?
At 11:28 in the lecture he makes
const FHitResult getFirstPhysicsBodyInReach();
What he the reason for this function being a const?
Iâm not sure if my response âbumpsâ the thread, but I would like to know too
A couple episodes down the line where weâre challenged to refactor our code, I created a method for calculating LineTraceEnd, although calling it inside of âGetFirstPhysicsBodyInReach() constâ gives me an error
Removing the âconstâ fixes the error and leaves me scratching my head, what was the point of const?
Declaring a class method as const makes sure, that it does not modify the instanced objects variables.
The compiler forbids it.
So if you get an error when using const you probably have some code in your method that modifies variables of the object.
Ben explained this in 33. Introducing the Const Keyword
Right: my error is the following when leaving method âGetFirstPhysicsBodyInReachâ as âconstâ:
E:\Documents\Unreal Projects\03_BuildingEscape\BuildingEscape\Source\BuildingEscape\Grabber.cpp(117) :
error C2664: âbool UWorld::LineTraceSingleByObjectType(FHitResult &,const FVector &,const FVector &,const FCollisionObjectQueryParams &,const FCollisionQueryParams &) constâ:
cannot convert argument 1 from âconst FHitResultâ to âFHitResult &â
When I remove âconstâ from âGetFirstPhysicsBodyInReachâ the error is gone.
It seems to have an issue with the following method within âGetFirstPhysicsBodyInReachâ:
GetWorld()->LineTraceSingleByObjectType(
OUTHit,
OUTPlayerViewPointLocation,
LineTraceEnd,
FCollisionObjectQueryParams(ECollisionChannel::ECC_PhysicsBody),
TraceParameters
);
I donât understand where the problem isâŚ
Kind regards, Peter
When a variable (like LineTraceEnd) is const, it means it cannot be changed
When a function (like your GetFirstPhysicsBodyInReach) is const, it means it cannot change any variables
Because you are trying to change âOUTHitâ inside of a function that is const, you get the error
Hope I made that easy to digest, it took me a while to understand const
Thank you Advent, that makes sense.