C++ typecast derived class to parent class?

For example, I have a function:

SomeFunc( TSubclassOf<BaseClass> Param)

And I have a derived class like:

class ChildClass : public BaseClass { ... }  

So I can call my function with child class like so:

ChildClass Item;
SomeFunc( Item );

But how can I typecast the ChildClass argument to the BaseClass inside my function?
I mean how to do this in UE?

SomeFunc( TSubclassOf<BaseClass> Param)  
{
    BaseClass* Item = (BaseClass*)Param;
}

TSubclassOf Param is going to pass the class of the item and not the item itself. Beware of this. If you want to pass a pointer to a function that takes it as a pointer to the base class you can simple use it that way:

SomeFunct(BaseClass* Item);

Anyways, to respond your question, to get the derived class as a pointer to your base class simply cast it with the Cast function, like so:

 BaseClass* Item = Cast<BaseClass>(Param);

Again, this is unnecesary if what you are doing is passing pointers. You do not need to cast a derived class object pointer to its base class in a function. Simply pass the pointer. In that case your function would look like this:

SomeFunct(BaseClass* Item);
{
  //Do work
}  

And would be called like this, for instance:

ChildClass* Item = NewObject<Item>();
SomeFunct(Item);

You should use casting only for downcasting. For instance if you want a pointer of your base class to be used as a pointer to your child class. Upcasting is not needed with pointers.

Hope this helps. Make it a great day.

1 Like