Call method of derived class



in the following example I need to call the function MainWindowTutorialApplication::myFunction() from MainWindow::closeButtonPressed(). How do I correct it?


class MainWindowTutorialApplication  : public JUCEApplication



    MainWindowTutorialApplication() {}    

    void myFunction() {}

    class MainWindow    : public DocumentWindow



        MainWindow (String name)  : DocumentWindow (name,




            centreWithSize (300, 200);

            setVisible (true);


        void closeButtonPressed() override


            // JUCEApplication::getInstance()->myFunction(); ???





    ScopedPointer<MainWindow> mainWindow;



Well, for example you could give your MainWindow class the MainWindowTutorialApplication object as a parameter. I.e. in the constructor of MainWindow.

Not sure if that is the best way, but it would work...


Depending on what you need myFunction to do (i.e. does it depend on members of MainWindowTutorialApplication?) you could make it static and call it using MainWindowTutorialApplication::myFunction() anywhere in the code that knows about MainWindowTutorialApplication. Otherwise, I'd go with what Alatar said and pass in and store specific instance as a reference or pointer in the constructor of MainWindow.

((MainWindowTutorialApplication*) JUCEApplication::getInstance())->myFunction();



Please don't encourage our beginners to get bad C++ habits!

At an absolute minimum this should be a static_cast, not a C-style cast.

But when you're doing this kind of thing, it's inevitable that you'll do the same thing more than once, so you should always create a special function for it and add some sanity-checks, e.g.

MainWindowTutorialApplication& getTutorialApp() noexcept
    auto* t = dynamic_cast<MainWindowTutorialApplication*> (JUCEApplication::getInstance());
    jassert (t != nullptr);
    return *t;



I know the ways to do this, but I do not know which approach is correct. I think is unnecessary MainWindowTutorialApplication passing as reference in the constructor of MainWindow. It seems to me that the a better way with dynamic_cast ( static_cast ) operator.

It is possible to use „event mechanism“ like „onCloseButton( std :: function < > func)“ ?