Wednesday, January 20, 2010

The easy way to call pre and post function execution code pieces

Well at times you want to execute some while you enter some function, something like enable or disable certain objects or set some flags before execution and reset them after you have finished this function.

The most straightforward way of doing it is putting code for it in the beginning and end of the function. But if this code of your grows in size and there are several return statements added to it, then you maintaining this code will become difficult.

So the easy way out ? Well its simple. Create a new class with just constructor and destructor. In the constructor call the code which you want to execute initially, and the destructor to have the post processing code. Make sure that copy constructors is made private just to avoid complications.


class magicalObject
            // do pre processing job here
            // do post processing job here
        magicalObjet(magicalObject & obj);      

void somefunction()
    magicalObject myMagicalObject;     // pre processing job done now

    // do your job

    // no worries the post processing job will be done my
    // magical object