Call method of derived class


#1

Hello,

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

Thanks.

class MainWindowTutorialApplication  : public JUCEApplication

{

public:

    MainWindowTutorialApplication() {}    

    void myFunction() {}

    class MainWindow    : public DocumentWindow

    {

    public:

        MainWindow (String name)  : DocumentWindow (name,

                                                    Colours::lightgrey,

                                                    DocumentWindow::allButtons)

        {

            centreWithSize (300, 200);

            setVisible (true);

        }


        void closeButtonPressed() override

        {            

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

            JUCEApplication::getInstance()->systemRequestedQuit();

        }

    };

private:

    ScopedPointer<MainWindow> mainWindow;

};

#2

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...
 


#3

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.


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

 


#5

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;
}

 


#6

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)“ ?

Thanks.