Why did getFirstPhysicsBodyInReach need to be const?

At 11:28 in the lecture he makes

const FHitResult getFirstPhysicsBodyInReach();

What he the reason for this function being a const?

1 Like

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?

1 Like

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

3 Likes

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

1 Like

Thank you Advent, that makes sense.

Privacy & Terms