Saturday, October 24, 2009

An example of Interface pattern in use

Interface pattern is a interesting pattern and only recently I realized the value of using it and where people put it into use.

One real interesting use of this that I found was in using callback functions for components.

Say you want to use a component A1 in a class B. But this component A1 needs to get some information from its user, class B, then we need a callback. How does one make sure that the right callback is provided by the implementer. Well interface pattern provides a simple solution for this.

To make to use of interface pattern, we need to implement an abstract class A2. This class should have the function which we want to use as callback as a pure virtual function. Now each class which needs to use component A1, should inherit A2 and implement the desired callback function in A2.

Example, implementation of this is as follows

class A2
{

public:

        void CallBackFunc() = 0;

}

class A1
{

public:

        A2 *user;

         A1(A2 *userClass)
        {

               user = userClass;

        }

        void action()
        {

              user->CallBackFunc();

        }

}

class B : public A2
{

       B()
       {

             A1 *newObj = new A1(this);

       }

        void CallBackFunc()
        {

             //Do something here

              return;

        }

}

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.

Wednesday, July 1, 2009

const Vs #define, what to use and when

const one of the features which was not present in C but was introduced in C++. Its interesting to know why would anyone use const to declare constant values and not #defines which are being used since ages and have done the work more or less without much trouble.

Well the problem with #define is that its a preprocessor directive. Which means it needs to be put in a .h file for sharing among different files. But if it just needs to be used in a single cpp file, it works like a charm. But imagine that you need to include it in several files. Then you are in a big mess. If you make a simple change in that .h file, the build process will compile all files that include the header file. Which in case of big projects can mean a lot of headache.

So welcome to const. This can help you get rid of this problem. Since these const variables are actually compiled and not used as in case of header files. There is no need to compile all files using const variables, provided you make use of forward declarations  in the cpp files.

Const does not mean that it does not have any downside. It does have a problem. If you have a large number of declarations they all take some memory and you now understand what it can lead to. But in most cases, const is actually better than #define. But you need to take that call.

Note: The above is based on my understanding. If you think otherwise, do let me know why.

Saturday, May 2, 2009

Why you should use forward declarations

Well I am sure you have always heard people telling you to use forward class declaration. I am not sure if you too have thought that what’s the point of it.

Well one best use case is in case of circular dependency. When you have a class A depended on class B and class B also references class A, you will be in a mess including header files in each other. So forward declaration would be a good way out of the mess, provided it meets certain conditions.

Another reason for using forward class declaration is that you will actually speed up the compilation time. Say you include class A as a pointer in class B and for that you have included header file of A in B. Then for any change in A, if it affects B in any manner or not, would lead to compilation of class B as well. This can be a serious pain point in case of large projects. If A has a forward declaration, then A would be compiled(obviously) and then at link time, compiler would make class B aware of A. 

But now the big question is, when can u not use forward declaration. Well answer to that question is very simple. Think like a compiler, in what situations would you be missing an actual declaration.

One of the reason can be when you are using the class as a base class. In that case u cannot determine the base class function  and the compiler cannot check for rules until it finds the declaration.

Another case is when you declare it as a member. In this case compiler has no clue about the size of memory to be allocated for this member. So forward declaration does not work here as well.

At times you want to define functions in the header file itself. In that case, if your function uses a forward declared class, it would throw a compile time error, because it has no clue about its properties.

Also its pretty clear that if you try and create an dynamically allocated object of class, forward declaration would not work if you try and call some function on that object. Again simply because the compiler would have no clue about that.

So friends its important that we use, forward declarations wherever possible. It does make life a lot more simpler, but then one size does not fit all Happy

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.

Saturday, March 28, 2009

When Multiple Inheritance is bad

We all see and know that Multiple inheritance is one of the most classy features of C++. Something that was sorely missed in Java which did not allow. Well recently I realized that its actually a good thing if we just stick with single inheritance. Why, well the reason is simple.

 Diagram1

So now say you are the creator of all the classes, A,B,C, X and Y.  In that case your best approach would be if it was such that there was single inheritance. In that case you would have several benefits. For example if there was such a case that at some point of time, you need to use some function in B from class Y, you would not be able to do it. A single inheritance would provide you the extra flexibility to do operations on the object C in the base classes.

Well this is debatable that you should always stick to single inheritance or not. My take is that one hat does not fit all. So based on the situation, we need to take a call and do what best solves the problem at hand.