Showing posts with label constructor. Show all posts
Showing posts with label constructor. Show all posts

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.

Example:

class magicalObject
{
    public:
        magicalObject()
        {
            // do pre processing job here
        };
        ~magicalObject()
        {
            // do post processing job here
        };
    private:
        magicalObjet(magicalObject & obj);      
}

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

    // do your job

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

Tuesday, April 14, 2009

Why pointers are so very important in C++

Pointer are the life line of any C/C++ programmer. The reason is not just the flexibility, but also the additional speed that a pointer adds to your program. The reason is simple, the constructor of your class is not called. Well its actually safer if you send any class object, since the actual object does not get modified. But then its a safe design and will lead to some penalty in terms of speed. Sometimes, all you care for is speed, then its important to understand what happens while a function is being called.

Well in C++ this is what happens when you call a function

1.  All registers are saved on the stack.

2. Stack is saved, usually by incrementing the stack pointer.

3. Parameters to the function are saved to the new stack.

4. Function execution starts

Well the reverse of thing happens when the function returns.

1. Parameters in the stack are destroyed.

2. Saved stack is retrieved, usually my manipulating the stack pointers.

3. All saved registers are restored.

As you can make from the above actions, there is an additional overhead of calling the constructor and destructor of the parameters. This is definitely not going to happen for free. There is a some penalty which you would take.

Its then upto you to decide what you want. Some safe programming or avoiding the penalty.