2
\$\begingroup\$

I’m stuck in understanding of usable actors from survivable c++ example. I have return Cast<AUsableItem>(Hit.GetActor());. I have class AUsableItem. And I have another class AUsableWeapon inherited from AUsableItem.

I have function Use() in both classes, so basically in the end it looks like Cast<AUsableItem>(Hit.GetActor())->Use(). Hit.GetActor() returns instance of AUsableWeapon. And when i do that ->Use() call, it goes into AUsableWeapon even though it was casted to AUsableItem. Problem is - I cant understand how exactly after casting to AUsableWeapon I get Use() called from AUsableWeapon.

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

That is the whole point of inheritance, that the method of the derived class is called. When AUsableWeapon redefines a method from its base class then it also has to ensure that a caller never has to worry about which method is called.

To do that, you usually use Super::Use() from inside your AUsableWeapon::Use() method, so it calls the method from the parent class and then does something in addition to that.

\$\endgroup\$
2
  • \$\begingroup\$ Thing is - i expected Cast to return me instance of AUsableItem instead of AUsableWeapon \$\endgroup\$
    – Avdept
    Commented Jan 12, 2016 at 8:12
  • \$\begingroup\$ I don't think that the cast actually changes the underlying object - all it does is to tell the compiler that you are allowed to call certain methods on an object. Which method is called then depends on the actual class of the object/which method were overriden etc. \$\endgroup\$
    – TheBrain
    Commented Jan 18, 2016 at 10:32
1
\$\begingroup\$

Your Use function must be declared as virtual. As the instance is of type AUsableWeapon virtual will ensure that AUsableWeapon's version of the Use function is always called even if it is casted to a base class pointer type.

Either make it non-virtual by removing the keyword or rename the function in both classes to something else like UseItem and UseWeapon.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .