Call a function without specifying the class?

In my project, the player can press the left button the mouse in order to interact with objects and actors in the game world. As of right now, I have a long series of If Statements in order to detect what Actor class the object is, and call the Interact() function on it. On all of the interactable objects, their unique classes all have an Interact() function that do different things depending on the object. For Example, when door is clicked it might open, or a lightswitch will activate a light.

So, my point is, instead of a long bloated list of If Statements, is there someway or setup I can implement that, on click, will check if the class has the Interact() function, and then call it if it does?

Hopefully that makes sense. Thank you for any responses!

It sounds like you have an “evil-if over type” situation which usually calls for polymorphism as a first step in C++. My first recommendation without knowing the specifics of your project would be to create an Interface “Interactable” and have your objects inherit/implement it which would remove your all of your if statements.

An interface is the easiest solution to your problem. In laymen’s terms, an interface means “this object will implement these functions” so even if your objects are different classes, if they implement the same interface you can cast to that interface and call functions on them.

HOWEVER this means that every class you have has to implement those functions and do whatever. Usually the “whatever” part is similar in many cases which is why I usually prefer having a UInteractComponent on my objects and when I interact, I grab that component and do my stuff in there. That component will have several interact types like Loot, Dialog etc. and one Generic interact function that owners can override and do whatever they want with it.