Virtual/Override and Inheritance

This is by no means comprehensive information on such a big topic, but a few key points are:

  • the ‘virtual’ specifier in a function declaration indicates that this function can be inherited/overriden in a derived class. It can still be accessed (called) from the child class even if it’s not virtual, as long as it’s not ‘private’ (it can be either ‘public’ or ‘protected’).

  • in a derived class you can override a virtual function of a parent class. All the ‘override’ specifier really does is throw a compile time error if no suitable function to override was found, like if you got the function signature wrong. The function would still be overridden even if you don’t specify ‘override’ if the parent function is virtual. Nevertheless it is good practice to specify override for functions you intend to override.

  • inside your overridden function you can still call the parent class implementation of the function, at any place in the function. UE specifically has a neat reflected way of doing this using the ‘Super’ keyword, e.g. Super::OnFire(); In vanilla c++ you would need to explicitly specify the base class.

  • What’s really the difference or point of virtual functions? What if OnFire wasn’t virtual? We could still define it just the same in both classes, and it would still work in the following case:



AWeaponBase* wbase = GetWeaponBase();
wbase->OnFire();

AWeaponRifle* wrifle = GetWeaponRifle();
wrifle->OnFire();


The difference comes when you’re calling a function of a derived class from a pointer to the base class:



AWeaponBase* wbase = GetWeaponRifle();
wbase->OnFire(); //if OnFire is virtual, then AWeaponRifle::OnFire is called. Otherwise, AWeaponBase::OnFire is called.


7 Likes