Running interface on a const pointer

Hi.

I’m having difficulty trying to execute an interface on a const pointer. The code is very simple and brief

	UFUNCTION(BlueprintCallable, Category = "AI")
	FVector GetFocalPointOnActor(const AActor *Actor) const override
	{
		return IPCVisibilityInterface::Execute_IGetFocalLocation(Actor);
	}

But I’m getting this error

error C2664: 'FVector IPCVisibilityInterface::Execute_IGetFocalLocation(UObject *)': cannot convert argument 1 from 'const AActor *' to 'UObject *'

The pointer had to be a const because I’m overriding a parent function.
I tried de-referencing it , but I still couldn’t get it to work. Any idea what I’m missing?

This error is not specific to interfaces. You cannot pass a pointer to const as parameter of non-const type, i.e., your interface would have to take an argument of type const UObject* instead of UObject*.

Is the IGetFocalLocation interface something that you control? If it is then the simplest solution would be to define its argument as const UObject* (or to define an overloaded method that takes a const UObject* in addition to the existing method).

If you do not control the interface but you are certain that Execute_IGetFocalLocation does not modify its argument you can const_cast the argument, but that’s a much inferior solution since you lose the compiler’s checks for const correctness.

You can’t call the method, since the method requires a non-const pointer and you give it a const pointer. You either have to call the method with a non-const pointer or change the method signature to take a const pointer.

You could also try to cast away the constness with const_cast, but I have no idea if that works in the engine, and it seems super hacky, and it kind of defies the whole point of const. I mean it seems like this method has a semantic problem: You are basically saying: This method takes an Actor, that cannot be changed and then pass it to a method that tries to change that Actor.

nooo you beat me by a minute :smiley:

I’d agree it’s not specific to interfaces. However there’s one thing with interface is that you don’t directly call the function, rather you call the Execute_Functionname. which is a generated function.

IGetFocalLocation actually accepts Actor, but because it’s an interface, the compiler generates the Execute functions. the generated function ‘Execute_IGetFocalLocation’ receives a UObject instead. In normal circumstance I would just let it take const.

1 Like