Sunday, April 19, 2009

using array of pointer to member function

Seems like a crazy at the first instance, but this is an amazing use of the facility provided by C++ which is called, pointer to member of a class. This can be a function or a variable. But where to use it. Well one of cases is when one needs to call different function of same signature based on some parameter. Surely this can be done via other trivial means as well certain situation may call for special measures. This can used in that case.

How to create and use it is taken straight out of C++ FAQLite . Link to specific page is here.

Say we have a class A as following

class A
public : 
    void a(int x);
    void b(int x);
    void c(int x);
    void d(int x);

//create array of pointer to member function
int ((A::*ptr)[4])(int x) = {&A::a, &A::b, &A::c, &A::d};

//using it in function
void testFunc(int val1, int val2)

So our testfunction will call a,b,c or d from ObjectOfA depending on the val1 with parameter val2. Though obviously there are better ways to do it, but then this is also one complicated but shorter(codewise) one.

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.