Thursday, November 19, 2009

C++ cast operators

Describe C++ cast operators

static_castis used to cast up and down the class hierarchy, conversions with unary constructors as well as conversions with conversion operators. It is similar to the C-style casts.

For instance, in the code below, a call is made to the operator int in class X

dynamic_cast is the C++ way of casting. It uses RTTI to determine if the cast is valid.

If we are attempting to cast to an incompatible pointer type, the result is a NULL.

If we try to cast to an incompatible reference type, an std::bad_cast exception is thrown.

The dynamic_cast must be un-ambigous.

dynamic_cast works only with polymorphic types (ie where the classes have at least one virtual function)

struct X
 {
     int value;
     virtual ~X() {}
 };

 struct Y : public X
 {
 };


 int main(int, char **)
 {
     Y anY;
     X anX;

     X & xRef = anY;
     Y& yRef = dynamic_cast( xRef );

     X& xRef2 = anX;
     try
     {
         Y& yRef2 = dynamic_cast( xRef2 );
     }
     catch( std::bad_cast&  e)
     {
         std::cout <<"Caught bad cast exception ! " << e.what() << "\n";
     }
     std::cout << "Program finished !\n";
     return 0;
 }


reinterpret_castAllows you to cast apples to horses.

const_castallows us to cast away the const or volatile from a reference or pointer. The target data type must be the same as the source type.


Thursday, November 12, 2009

Delegates and events in C#

What are delegates and events in C# ? Delegates

Delegates in C# are objects which points towards a function which matches its signature. Delegates are reference type used to encapsulate a method with a specific signature. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure.

Here are some features of delegates:

  • A delegate represents a class.
  • A delegate is type-safe.
  • We can use delegates both for static and instance methods
  • We can combine multiple delegates into a single delegate.
  • Delegates are often used in event-based programming, such as publish/subscribe.
  • We can use delegates in asynchronous-style programming.
  • We can define delegates inside or outside of classes.
  • Delegte declarations are like ordinary declerations and can be public, private internal etc.
  • Two delegates are compatible if their parameters are of the same type, order and modifiers and their return types are the same.
  • Delegates can be combined using the + and += operators. When two delegates are combined, the resulting delegate contains all the callable entities from both the delegates. Similarily, delegates can be removed using the - or -= operators.
  • Delegates can be compared.
  • delegate methods are invoked synchronously.
  • If such a delegate invocation includes reference parameters, each method invocation will occur with a reference to the same variable and changes to that variable by one method in the invocation list will be visible to methods further down the invocation list.
  • If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.
  • If an exception occurs within a delegate and the exception is not caught in the method that was called, continues in the method that called the delegate. If the exception is not handled in the called method, delegate processing is abandoned and other functions in the delegate are not called.

To declare a delegate, use the delegate keyword like:

    // declare a delegate
    public delegate void MyDelegate(int x); 

    /*
     * Declare a function which takes a 
     * delegate parameter. 
     */
    void MyFunc( MyDelegate inDelegateParam)
    {
         inDelegateParam(100); // Call the delegate
    }

    // Create a function with the same signature 
    // as the delegate decl
    void someFunc(int p)
    {
    }

    static void Main(string[] args)
    {
        MyDelegate aDel = new MyDelegate( someFunc);
        MyFunc( aDel );
    }

When we declare a delegate, the compiler automatically creates a class derrived from System.Delegate. A delegate instance encapsulates one or more methods, each of which is a callable entiry. For instance methods, the callable entity consists of the instance and the method.

When we invoke a delegate, all the callable entities get called.

Events

Delegates are used to create events. here is an example of an event

        // First declare a delegate
        public delegate void MyDelegate(int x);

        // now, the event
        public static event MyDelegate m_del;

        public static void testit()
        {
            m_del += new MyDelegate(EventFunc);
            m_del(2);
        }

        // This is the event handler
        static void EventFunc(int x)
        {
            Console.WriteLine("in event handler!!!!\n");
        }

Thursday, November 5, 2009

Singleton in multi-threaded environment

Question: How would you write a singleton in a multi-threaded environment?

In a singleton, there are two race conditions; one where the instance is created and the other when we access instance data. The method which creates the singleton instance must be made thread safe. Here is an example: