user45146 user45146 - 3 months ago 8
C++ Question

What are advantages of using application class?

I've seen many c++ codes which use an application class something like this:

class MyApplication : Application {
private:
int privateVariable;
public:
void run() {
run...
}
~MyApplication() {
cleanup...
}
}

int main() {
MyApplication app;
app.run();
}


instead of:

int main() {
int variable;
run...
cleanup...
}


What are advantages of using the application class? One that I can think of is that I don't need to pass every variable as a function parameter (thus easy to extract functions). Is there any other advantage or disadvantage? When is this style recommended or not?

I tried to search about this, but I couldn't. Any advice would be really appreciated.

Answer

At least three things.

  1. There may be several application classes, in a hierarchy like

    AbstractApplication
        GUIApplication
        ServerApplication
        ConsoleApplication
    

    Using OOP and inheritance is natural here, there is a lot of shared code, which doesn't need to care about the exact type of the application object. The shared code would typically be event loop (in the run method), as these kind of applications are generally event driven.

  2. Event handlers and other callbacks are easily implemented by overriding virtual protected methods in the application class, as needed:

    class MyApplication : Application {
        // ...
    protected:
        void someEvent(Event *event) {
            if (event->type()==Application::InterestingEvent) {
                // Do something about it
            } else {
                // just pass the event to super class implementation
                Application::someEvent(event);
            }
        }
    }
    

    Here the callback needs to be defined just once, in the subclass of Application object, and it will just work. With some other ways to implement this, the framework developer might need to keep a separate callback table (now taken care of by vtable of the object), and the application developer would need to add a separate callback registration.

  3. Cleanup is cleanly and deterministically taken care of by RAII. You don't need to care about the exact type of the application object, because it knows this itself, and compiler takes care of it.

Comments