Łukasz Baran
Łukasz Baran

Reputation: 1239

C++ Calling parent virtual function from pointer

I have this code:

void FAuCoreEditorModule::OnAssetEditorOpen(
    UObject* EditObject
  , IAssetEditorInstance* Toolkit)
{
    FName NAme = Toolkit->GetEditorName();
    if(Toolkit->GetEditorName() == "CurveTableEditor")
    {
        FAssetEditorToolkit* AET = static_cast<FAssetEditorToolkit*>(Toolkit);
        AET->FAssetEditorToolkit::RegisterTabSpawners(AET->GetTabManager().ToSharedRef());
    }
}

The Toolkit is of type ICurveTableEditor.

RegisterTabSpawners

Is virtual function in FAssetEditorToolkit. CurveTableEditor implements it, but never call to parent. I wanted to call parent implementation, without modyfing original source code. Came up with this:

FAssetEditorToolkit* AET = static_cast<FAssetEditorToolkit*>(Toolkit);
AET->FAssetEditorToolkit::RegisterTabSpawners(AET->GetTabManager().ToSharedRef());

It this legal ? Or it just work by accident ?

Upvotes: 0

Views: 74

Answers (1)

eerorika
eerorika

Reputation: 238341

It this legal ?

Potentially yes. Not necessarily.

Static downcasting is allowed if IAssetEditorInstance is a non-virtual unambiguous base of FAssetEditorToolkit and if the pointer is truly to an object of such type (or a type with such non-virtual base).

If some of those restrictions are not satisfied, you can use dynamic_cast instead (as long as the base is polymorphic). Make sure to check whether it returns null or not.

Upvotes: 2

Related Questions