Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Thursday, July 9, 2009

The importance of Interface classes

I am sure you might have heard about interfaces. But then why do you need them. You anyways are going to implement those classes. Why take the unnecessary overhead of writing interfaces for them as well.

Actually its not necessary to write a interface class for all classes that you write. But there are certain cases when its much much better if you have them in place.

First what are interface classes. Well this is a base class which has pure declaration of all the public methods need in the target class. All these methods are make pure virtual functions. No implementation is added to this class. For example if you write a class Time, you would want to declare an interface named, ITime. So the class declarations would be as follows.

class ITime 
{
      public : int getHour() = 0;
                   int getMinute()= 0;
                   int getSecond()= 0;
                   void setHour(int hour)= 0;
                   void setMinute(int min)= 0;
                   void setSecond(int sec)= 0;
};
class Time: public ITime
{
      public : int getHour() = 0;
                   int getMinute()= 0;
                   int getSecond()= 0;
                   void setHour(int hour)= 0;
                   void setMinute(int min)= 0;
                   void setSecond(int sec)= 0;
      private: int m_hour, m_min, m_sec;
};

The interface class has no implementation but the concrete class does. Concrete class contains all additional private member variables needed as well as constructors and destructors, as needed.

When do you need it? For classes which are instantiated at a few locations but used at a lot of other places, it makes sense to create interfaces for them.

But why do all this circus. Well the reason is pretty straight forward, to allow users of this class not care about whatever is there in the actual implementation. All internally used methods and variables are not known to the user of this class. Also since the concrete class headers are not included at all places where this class is being used, changes in internal implementation need not lead to compilation of each of the other classes. Only if something is changed in Interface class, recompilation would take place in all places else its a faster process.

This is more or less what I understand as a need for Interfaces. Please do let me know if you think otherwise.

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)
{
    ObjectOfA.*(ptr[val1])(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.

Friday, October 24, 2008

I know this code does not work as expected

Well I came across this amazing piece of code which does not crash as expected.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    int array[4];
    for(i=0; i<=8; i++)
    {
        array[i]=0;
    }

  return 0;
}

This seems to be perfectly ok code. Obviously it falters at the point where I set value to the array at index 4 - 8. Everyone would generally expect it to crash, but amazingly it did not. I tried it on wxDevcpp and it runs in an infinite loop. I was amazed at why it did. Its interesting to know what happened.

Let me first explain what actually happened. Casual observation revealed that the for loop runs forever. It seems that value of i is reset to 1 each time it reaches 7. Wow this is amazing. But what happened.

What happened is simple. Our incorrect program overwrites 'i' when it tries to put zero at array[7]. That because &array[7] is same as &i. Why? well thats because our amazing manner in which local variables are stored in the stack. So what happens is i  is there in the stack some place above array and we happen it make is zero each time.

Amazing simple reason why this kind of crappy thing happens.

Thursday, March 6, 2008

virtual function -- the key to OOP

I actually never understood this concept until I had to code something in it. It was really awesome to realize what this virtual keyword can do. I actually believe that we should make all our class member functions virtual. Though this may generate some sort of an overhead but I feel that the compiler optimization should take care of it. The main use of this virtual keyword is in cases where we need to reuse certain classes. Often the framework in which we are working in identifies a single base class. so now when this framework wants to make use of the new class, it can do so without any problem. Though the framework calls the same function it would now be able to access the function modified for the new class. Often when we have written code for drawing certain objects on the screen, we would have anticipated line, circle, triangle and a polygon. But later we realize the need for having quadrilaterals and squares also as they are frequently used. So in this case had we made use of a base class shapes, which would have had a virtual function called draw. The framework would just call 'draw' for the entire list of shapes it had. Since the 'draw' is virtual, you can expect the object specific 'draw' to be called. So you can easily extend you library. This is also called factory pattern. But this is not the only pattern to use virtual, there are others also but this example give us a very good reason to why we need virtual function, though there are ways to live without it also. But why use a knife to cut a tree when u have an axe.

Friday, February 29, 2008

inline functions, the good, bad and ugly

I learnt while reading from C++ FAQ Lite at http://www.parashift.com/c++-faq-lite/ about the good, bad and ugly aspects of inline functions. So here they are

Inline function can make you code faster if used, but then if its used a lot of places as inline function, the code bloats up. This can also lead to more page faults and hence leading to serious performance issues. Sometimes function optimizations can actually lead to a smaller code being generated because code for function calls(basically stack usage) is optimised.

Did I say page faults can increase, but then if there were two function on different pages, then thrashing could have been more without inline functions. Also its more likely that code would be at the boundary of cache, so cache memory thrashing is induced there.  But then again if the code is at right in the middle of the cache then fetching code of another function in another page would take toll on memory via thrashing.

So is inline good or bad. Now that something very subjective I would say. Just like not every garment looks beautiful to the customer, inlineing is also based on the usage. A simple direct answer may very well be wrong.

Tuesday, February 26, 2008

inline function, a move over #define

One the feature of C++ that I find very cool is inline function. It actually kills all those crazy interview questions which are asked just to confuse you over brackets. I dont remember ever using the complicated #define in C to anything more than example programs. Crazy part of inline funtion is that though u code almost as a normal function call but it gives the advantages of writing code right where u called the function. No more making sure that you have brackets in place and how its going to expand at all the places, how its going to take in the parameters passed to it, how will the return value be determined. Dump all that. How to stuff is here

void foo()
{
  int a,b, c;
  c = bar(a,b);
}

inline int bar(int a, int b)
{
  //Just do something here
   return something;
}

So you have the function foo calling function bar, but as bar is inline code for it would be placed right where it was called in foo. So we see how inline function has simplified life in C++. Any question of yours in this regard would be appreciated and I would try my best to answer it.