Archive for the 'Reference' Category

Print out all odd number from 1 to 100 using a for loop!

The very first thought likely to hit will be that of taking mod 2(%2) of numbers from 1 to 100 in a loop and checking whether it yield an remainder or not. But there is even better a way to deal with it.

                 for( unsigned int i = 1; i < = 100; i++ )
                        if( i & 0×00000001 )
                                 cout << i<<” “;

The catch is, only odd number’s binary representation ends with ‘1’.Check the below table

Dec Hex Bin
000 00 00000000
001 01 00000001
002 02 00000010
003 03 00000011
004 04 00000100
005 05 00000101
006 06 00000110
007 07 00000111
008 08 00001000
009 09 00001001
010 0A 00001010
011 0B 00001011
012 0C 00001100
013 0D 00001101
014 0E 00001110
015 0F 00001111

Inside the Googleplex

A short 5 min video inside Google’s Mountainview office. Inspiring as always; this is a good watch. 

 

Some ambiguous virtual function calls ~ Part1

In this article I will be discussing one funny virtual function call.Consider the below code snippet:-

class V
{
      public:
      virtual void f() { }   //Virtual function
};
 
class A : virtual public V
{
      void f() { }           //NON Virtual function
};
 
class B : virtual public V
{
      void f() { }           //NON Virtual function
};
 
class D : public A, public B
{ };
 
int main()
{
  D d;
  V* vptr = &d;
  vptr->f();// which f(), A::f() or B::f()?    
}

 

When you try to compile the above code snippet you will get the following error dumps.

error C2250: ‘D’ : ambiguous inheritance of ‘A::A::f’
error C2250: ‘D’ : ambiguous inheritance of ‘B::B::f’

Let’s analyze this scenario a bit deeper. What I have done is I created a derived class (D) that inherits from two non virtual bases (A,B) that are derived from a virtual base class(V).

     V
    / \
  /     \
A        B
   \     /
     \ /
      D

In short its forms a deadly beautiful diamond with Class V at the top which has a Virtual function f() with two branches formed by class A and B. Both of these classes overrides the virtual function f().Do note that in class A and B the over ridden virtual functions are non virtual. Now Class D inherits class A and B. The issue is when f() is called by an object of D will it call the F() implemented by B(D::B::f)or the one implemented by C(D::C::f).Moral of the story - Never try this :D !

Related Reading:-

Template specialization

Template specialization

Templates are a great way of generic programming.Generalized set of functions/classes can be used from the STL or you can go create one for yourself.But in every genral situations there might be exceptional or special situatiions in which u want a specialized reaction,not the usual one.To sight an example conside creating a template class string.A class which encapsulate an (char,unicode etc) array with whole spectrum of functions to manupulate it.But consider the situation in which you are going to store arabic string in the same :).Dont forget arabs read/write from right-to-left and imagin a situation in which our dear arab says insert at position 0 like String::Append(0,arb) will it insert at the left ya right.So in situations like this we need specialized templates which accompanies the main template to deal with special situations like this.

Let see how this string template will loook like withe the specialization for arabic languages

template<class E>
class String
{
Public:
   E GetAt( int nIndex ) const  {    //General:for languages written from right to left }
   void SetAt( int nIndex, E ch ){     …    }
 .
 . 
};

template<>
class String<Arabic>
{
Public:
  Arabic GetAt( int nIndex ) const   {   //Special case:for languages written from left to right}
  void SetAt( int nIndex, Arabic ch ){     …           }
 .
 . 
};

Do note the empty ‘<>’ after keyword ‘template’ and in the next line <Arabic> tag  affixed with class name String.

Reference to Pointers

Have you ever come across declarations like int* &var. I guess you last spotted it in one of your framework function definition. This little code is called a reference to a pointer. To understand what it means all you need to know is what exactly is the difference between a ‘reference’ and ‘pointer’. For that purpose this example of reference to a variable will help

void swap(int& i, int& j)
  {
       int tmp = i;
       i = j;
       j = tmp;
  }
 
 int main()
  {
       int x, y;
      

       swap(x,y);
      

  }

Here i and j are aliases for main’s x and y respectively. In other words, i is x — not a pointer to x, nor a copy of x, but x itself. Anything you do to i gets done to x, and vice versa. In case of pointers it’s a separate ‘pointer variable’ which points to ‘our variable’. If u change the pointer variable value noting happens to the variable it points to. So as Marshall Cline says ‘please do not think of a reference as a funny looking pointer to an object’ 

Now you know what exactly a reference is; just think of a reference to a pointer. Its simply is the reference for the pointer variable;just a new name for our old pointer.

Spin buffers

Have you ever thought of a situation in which two threads need to communicate between each other? Let’s suppose one is a producer thread which produces data which will be used by a consumer thread. The obvious method to tackle this issue is to keep a common buffer right between them where the producer dumps its data into the buffer and the consumer reads the same. The one and only over head involved is that of, when the write operation is done the buffer will be locked by the producer thread. So the consumer thread has to wait until the buffer is released before it starts reading. This approach is fine until situation become some thing like the number of transactions between the threads goes around few thousands/sec. In fact situations like that occurs very frequently in game servers which require thousands of requested to be handled on per second basis. In such demanding situations the performance seem to come down drastically just because the consumer thread is put on hold when ever a write operation is on.

Classic Approach  

One good  solution for this problem is the Ring buffer. The idea is simple and classy. They use 2 pointers one for read and one for write. Using write pointer the data is written into the buffer while the read pointer reads the written data. When the read pointer and write pointer points to the same location, the buffer is empty. One important condition that needs to be checked out is that of the read pointer overtake write pointer, you know what happens ;)

The concept of Spin buffers is a direct extension of the Ring buffer. Spin buffers contains three internal “ordered” buffers. The buffers are ordered as 0, 1, and 2. Two pointers are maintained — one that points to a buffer that a reader reads from, and another one that writes. At any time there can be an assigned read buffer (R), an assigned write buffer (w), and free one (f). The buffers can be implemented as fixed-sized arrays.

 Spin_Buffer 

Now lets take a look at how write method is implemented:

  1. Put the item into the write buffer.
  2. If the next buffer is free, make the free buffer become the write buffer, and the current write buffer becomes free. 

It’s just the vice-versa with read method: 

  1.  Read the item from the read buffer.

  2.  If the current read buffer is empty and the next buffer is free, make the next buffer the read buffer, and the current read buffer becomes free.

 But you might be thinking where is that big advantage that you where hyping about. Look closely and you will notice the whole idea doesn’t involve any level of synchronization between the read and write methods. This means there is no dependency on each other and no one waits for the other. No locks means no wait means lots of time saved.

‘Model-View-Controller’ - A birds eye view

This is one of the most popular design patterns which have been widely adopted in applications which require multiple views of the same data. Typical examples of such applications are web based client-server applications in which many servers are busy browsing through our database and presenting data in different flavors to please a million users staring at their browsers. 

The primitive and blunt way of creating such applications was to integrate whole of the view and the logics into a single layer which is tightly linked to each other and also to the data representation back in the database. So when ever a change occurs at the database layer it directly affects the code written at the logics level since they are dependent on each other. Similar is the situation when you try to make a UI change you are unnecessarily ploughing through the logics code. It just mess-up the whole production in fact it becomes impossible to maintain and test such applications. 

With MVC pattern, first and foremost aim was that of a clean separation of objects into one of three categories — models for maintaining data, views for displaying all or a portion of the data, and controllers for handling events that affect the model or view(s).Model is a data representation which holds ALL the data of the application structured based on the domain. In fact it represents the whole of the data on which the application stands on. The controller is the logics part which  handles events triggered from the browser and makes corresponding changes to the model/View. 

The MVC abstraction can be graphically represented as follows.

MVC 

Events typically intimates the controller to change a model, or view, or both. Whenever a controller changes a model’s data or properties, all dependent views are automatically updated. Similarly, whenever a controller changes a view, for example, by revealing areas that were previously hidden, the view gets data from the underlying model to refresh itself.

Lets explain the MVC pattern with the help of a simple component which consists of a text field and two arrow buttons that can be used to increment or decrement a numeric value shown in the text field.

 MVC_example

The data is held in a text model that is shared with the text field. The text field provides a view of the current value. Each click on the arrow button  is an event source, that triggers an action event every . The buttons can be hooked to an action listener that eventually handles that event. Depending on the source of the event, the action listener either increments or decrements the value held in the model — The action listener is an example of a controller.The text model represent the model and the text box control - the view.

PS : Dig more on MVC here!

Evolution of programming Language!

I got this interesting picture about the language evolution in my ABAP objects training session. Quite an evolution right!.(Click the pic for an enlarged image). 

Lang_Evolution

The NUXI problem

Before we get into any details I think it’s worth a discussion what exactly is the difference between ‘Data’ and ‘Data representation’ in computer. When you see the representation ‘10′ you understand that it represent count ten. When you see the roman letter ‘X’ then also you interpret it as count 10.So ‘10′ and ‘X’ are data representation of same thing - count 10.In the world of computers also they have their own data representation, i.e. binary format. The count ten can be represented using  1 byte-00001010,which the computer recognizes as count 10 every time it sees this bit pattern.

There is no problem when reading a single byte because all computers read the bit patterns the same way. But not all the data representation can be done using 1 byte. Take for example a short variable form C/C++. It requires 2 bytes to represent one short variable.

Now the problems starts - when you read multi-byte data, where does the biggest byte appear?
•Big endian machine: Stores data big-end first. When looking at multiple bytes, the first byte (lowest address) is the biggest.
•Little endian machine: Stores data little-end first. When looking at multiple bytes, the first byte is smallest.

Like the decimal ‘10′ and roman ‘X’ represent the same thing, the Big and Small endian representations represent the same data but with different bit patterns and this creates problem when transmitting data between machines which has different byte-sex.

Let’s illustrate it with an example where we try to store the word UNIX in two consecutive short variables

short *s;    // pointer to set shorts
s = 0;        // point to location 0
*s = UN;  // store first short: U * 256 + N
s = 2;       // point to next location
*s = IX;   // store second short: I * 256 + X
On a big endian machine we see
Byte:     U N I X
Location: 0 1 2 3

On a little-endian machine we would see:
Byte:     N U X I
Location: 0 1 2 3

In the second case even though the bytes are stored “backwards” in memory, the little-endian machine knows it is little endian, and interprets them correctly when reading the values. But what happens when u pass a data from little-endian machine to big endian machine. The big endian machine reads UNIX as NUXI and that may be the beginning of a big problem .And this exactly is called the NUXI problem.

And the solutions:-

•The easiest approach is to agree to a common format for sending data over the network. The standard network order is actually big-endian.
•The other approach is to include a Byte Order Mark (BOM) before every piece of data which is sent across the network
 

3 ways to swap variables without temp variable

I bet this question has been asked more than a trillion times in the history of technical interviews and it sounds…..”How to swap variable values with out using a temporary variable?”..as simple as that…ooch…but how?

The most obvious way of doing a swap is by declaring a temp variable

             temp = I;

                   I = J;

                   J = temp;

But when you say no additional variables to be used, you can always use this age old trick           

                  i =  i  + j;

                  j =  i  -  j;

                  i =  i  -  j;

This has more flavors to follow like, using * / combination instead of +  -

                  i  =  i  *  j;

                  j =  i   /  j;

                  i =  i   /  j;

And the good news is that, the best of all is yet to come…. the XOR trick

                 i  =  i  ^  j ;

                 j   i   j;

                 i   i  ^  j;

This one works just fine and is the perfect one suited for any primitive variable types.

So next time some one gives you an intelligent look after this question…don’t forget to prick his ego.

Some thing about Private Destructors

Many may be wondering why you need to make a destructor private. After all you created it for divine uses such as returning the used resources back to the resource pool which protect you from memory leaks and dangling pointers. Then why do you want to torture yourself by making it private and unavailable.

The answer to the above questions becomes clear in the following scenarios..

Scene1:-When you want to create non inheritable-Final Classes
It could happens that you want your class not to be inherited by any other class i.e., to create a final class. For making a class final all you have to do is make the class’s constructor or destructor private. Since in a class there can be any number of constructors where as it can have only one destructor, it’s easy to keep the single destructor as private and make the class Final

Scene2:-While using Reference Counting Objects
As you have guessed what a reference counting object is, its an object that tracks the number of references to itself, and destroys itself when none of the references point toward it. Making it simple, the object may be in use by more than one reference simultaneously. Imagine the situation in which the destructor of this object is public and as  one of the refrence is released which innocently calls the destructor which is public and destroys the object. This could result in situations like the object being destroyed and other references still pointing to our dead object. To avoid such situations we make the destructor private and provide alternate  function which will be careful enough to invoke the destructor only if the reference count is 0.

class ABC
               {
                  private:
                    int RefCount;
                    ~ABC();

                   public:
                    ABC();
                    void incRefCount() { ++RefCount; }
                    void decRefCount() { if (–RefCount <=0) delete this; }
              };
This class definition is just for the purpose of demonstrating what a reference counting object’s class would look like. It can be further enhanced by avoiding situations like multiple calls to decrefCount(),and can be even restructured by deriving the class using a friend class.

Inside Virtual Functions

All are familiar with what a virtual function is; a member function of a class which can be overridden by any class which derives from it. To put it in even simpler words, member function that is declared with the keyword virtual .Before we have a peep into how a virtual function works lets have a brisk overview of what a virtual function is.

In case of regular member function the function to be called is resolved at compile time itself depending upon the type of the pointer used to call the object’s function. But with virtual function the function call is not based on the type of the pointer used to call the object’s function but solely on the object it points to. This happens dynamically at the run time using virtual tables & Virtual table pointers. Feeling bit confused? Let’s resolve it with an example.Take a look at the following class inheritance:-

             class Base
                {
                   private:

                   public:
                     void output(){cout<<”Base Output!!\n”; }
           
                };

            class Derived:Public Base

                {
                   private:

                   public:
                      void output(){cout<<”Derived Output!!\n”;}

                };

Notice here that the functions are non virtual and have identical function names.
Now let’s check the output for the following codes.

int main()
{
 Base *pB=new derived;      //Base Pointer pointing to Derived object
 pB->output();
 return 0;
}

Output:-
Base Output!!
Press any key to continue

Note that the Object is of the type derived where as the pointer referencing it is of the type Base.
Now as I am calling the output function from the base pointer, even though it points to a derived object, the base function is invoked. This is because during the compilation the base::output() function  is statically typed to the base class function call.

To prevent this from happening we insert a virtual keyword before the out put function in the base class…

virtual void output(){cout<<”Base Output!!\n”;}

Now the output becomes:-
Derived Output!!
Press any key to continue

Here there is no static typing. The trick here is an implementation of a new technique involving virtual tables and virtual pointers for implementing dynamic binding.

Take for example a class which has 10 virtual functions. The first thing the compiler does is to create a virtual table (vtable) exclusively for that class with 10 entries where each entry holds a memory address where the corresponding 10 virtual function are implemented. This can be visualized as an array of function pointers as follows:-

  className::__vtable[10]={&Base::v0,
                                                   &Base::v1,
                                                   &Base::v2,
                                                   &Base::v3,
                                                   &Base::v4,
                                                              .
                                                              .
                                                              .
                                                    &Base::v10
                                                   };

The point here is, when ever this class is inherited, a new virtual table is created for the derived class and if any of the virtual functions are overridden the function pointers in the new vtable will be overwritten with the new address which points to the new function implementation. Do keep in mind that for every class which implements/inherit virtual functions will have only 1 vtable per class.
Now you know that the class with virtual functions has a vtable and you create an object of that particular class. Some thing interesting happens here also. A new virtual pointer has been inserted into the class structure and is a part of every object created from that class. This virtual pointer points to the vtable of the corresponding class. So if you create 1000 objects of the class XYZ each object will have 1 virtual pointer and all of these 1000 pointers point to a single vtable owned by class XYZ. The class modification by the compiler and virtual pointer insertion into objects are hidden from the programmer. It can be visualized as an invisible data member being inserted into the class structure which points to the class’s vtable. Some thing like this:-

  class Base {
                            public:
                            …
                              FunctionPtr* __vptr; //Inserted by compiler
                                                                      //which points to  vtable
                                                                                                                                                   
                            …
                            };

The compiler also inserts a constructor modification so that when ever a new object is instantiated the newly inserted virtual pointer will be initialized to the starting address of the vtable owned by that class.Base

Base::Base() :__vptr(&Base::__vtable[0])   
 {
                                 //Base class constructor initializing
                                 //virtual pointer__vptr
 }

 

Now you know what all extra code insertions  are done by compiler to a class possessing virtual functions, its time to see the mechanism involved in a virtual function call. It involves just 3 steps-’Fetch-Fetch-Call’

Fetch1->Gets the Virtual pointer from the object and load it into the registry.
Fetch2->Gets the function pointer address into the registry from the   Vtable
Call      ->Call the function located at the address in the registry

Fetch1 Loads the Virtual pointer from the object into a registry. Now with this pointer we locate the vtable. In fetch2 the aim is to retrieve the function’s address from the vtable. For example if you want function no.3 from the v table we can calculate it by:

        VirtualPointerValue+3*(size of function pointer)

This will return you the address where the function implementation is- load this information into a register. Now it’s the last step-call the code at the location specified by the function pointer in the register to see your virtual function in action.

Related Reading:-

Sister Class’s cross-delegation

Consider the below code in which the Mom class is inherited by Bro and Sis class virtually. Bro class implements the virtual function Drive() where as Sis class implements the  virtual function Sing().

# include <iostream.h>

class Mom
{
public:
 virtual void Drive()=0;
 virtual void Sing()=0;
};

class Bro : public virtual Mom
{
public:
 virtual void Drive()
 {cout<<”I am driving”;}
};

class Sis :public virtual Mom
{
public:
 virtual void Sing()
 {
  cout<<”I am singing $$$$$$$$$$\n”;
 }
};

class Join :public Bro, public Sis
{
 
};

int  main()
{
 Join *pJ=new Join();
 Bro *pB=pJ; 
 pB->Sing();
 return 0;
}
Now in the main function the Join class’s pointer pJ is assigned to Bro pointer pB and the Bro pointer is calling Sing() function which it has never implemented. Just check the following output for a surprise.

Output:
I am singing $$$$$$$$$$
Press any key to continue

How can this happen? The Bro class has never implemented the Sing() function nor is it aware of existence of a class named Sis and its implementation of Sing() function. Then how Bro object successfully calls a Sing() from Sis class? This particular phenomenon is called ‘cross delegation’ and is an interesting features in polymorphism.

Related Reading:-

  • Inside Virtual Functions
  • Some ambiguous virtual function calls - 1
  • Virtual Inline functions

  •  

    July 2008
    S M T W T F S
    « Mar    
     12345
    6789101112
    13141516171819
    20212223242526
    2728293031  

    Categories

    Blog Stats

    • 29,660 hits

    Last 100 Visitors

    Map IP Address

    Map IP Address