Technical Interview Questions

The largest pool of technical questions with answers, explantions, code and detailed analysis

Archive for December, 2006

Constructors: Copy Constructors, What, Why, How, When … (C++)

Posted by tekpool on December 22, 2006

As the name suggests, a copy constructor is called whenever an object is copied. This happens in the following cases:

  • When an object is create from another object during initialization (Class a = b)
  • When an object is created from another object as a parameter to a constructor (Class a(b))
  • When an object is passed by value as an argument to a function (function(Class a))
  • When an object is return from a function (Class a; … return a;)
  • When an exception is thrown using this object type (Class a; …. throw a;)

Whenever an object copying scenario like the ones above is encountered, the copy constructor is invoked. A copy constructor can be either user defined or compiler defined. If the user does not define a copy constructor, then the default compiler defined copy constructor will be invoked during object copy scenarios. The default copy constructor is a bit-by-bit (member wise) copy. But often you will encounter situations where this is not desirable since this is just a shallow copy and sometimes you do not want an exact copy or you may want to do some custom resource management. 

Class t1; 
Class t2=t1; // Copy Constructor is invoked 
Class t3; 
t3=t1; // Assignment Operator is invoked 

In the Code snippet above, the constructor is invoked twice, during the creation of objects t1 and t3. (Creation of t2 invokes the copy constructor). The destructor is invoked 3 times though. In cases like these, if the constructor allocates memory and the destructor frees it, you will see the t2’s destructor will try to delete already deleted memory, if t1 is destroyed before t2 or vice-versa. Meaning, you are hosed. To prevent this, a user defined copy constructor needs to be provided. which doesn’t do a simple bit-by-bit but rather assigns memory specifically for the object and does a deep copy if required.

To define a copy constructor for a class T, a constructor of the following format needs to be defined.

Class T 
    T(const T& t) 

You need a reference because if it were T(T t), it would end in a infinite recursion. (Was that an oxymoron?). const because you are not changing the object in the constructor, you are just copying its contents

Some Rules of Thumb:

  • Don’t write a copy constructor if a bit-by-bit copy works for the class
  • If you defined your own copy constructor, it probably because you needed a deep copy or some special resource management, in which case, you will need to release these resources at the end, which means you probably need to define a destructor and  you may also want to think of overloading the assignment operator (beware of self-assignment)

Posted in C++, General, Microsoft, Progamming Languages | 24 Comments »

Constructors: Error / Exception Handling in Constructors

Posted by tekpool on December 8, 2006

Constructors do not have return type and so they cannot return error codes. How are errors or exceptions handled in constructors? What if the calls that you make in the constructor can actually throw exceptions? How do you let the caller know something bad happened in a constructor?

There are a few ways to do robust error/exception handling in constructors

  1. Do as little in the constructor has you can. Then provide an Init() function in the constructor, which does the normal initialization stuff. The user can then call this function after creating an object. The problem here is, its up to the user to actually call the Init() function. The user could potentially miss this step, making this method error prone. However, there are a lot of places where this methodology is used. You are trying to eliminate error handling in the constructor by using this method
  2. Another way to do this is by putting the object in a Zombie state. This is one approach you can take especially if you do not have the option of using exceptions. When you go with this option, you will also to do provide a function that will check the state of the object after construction. The downsides to this option is that, its up to the user to do these checks and the users will need to do this every time one attempts to create an object. It’s usually always better and cleaner to throw an exception instead. Use the Zombie option as a last resort.
  3. The downsides to the above methods can be reduced by making the constructor private or protected, expose a CreateInstance() public method, and do all the error handling here rather than leave it to the user. But sometimes, its not possible to handle all the error conditions in a generic manner and you will need to throw an exception.
  4. If an exception is thrown in the constructor, the destructor will not get called. So you need to handle and clean up as much as you can before you leave the constructor. The best way to do this is using the “resource allocation is initialization” technique. I will cover this topic separately in a future post. But the basic idea is to assign resource allocation and cleanup to other objects. Basically, you are trying to get allocation out of the way (indirect) so that you don’t have to do it explicitly. When you don’t allocate something directly, you don’t have to release it either because it will be done by the component or class who deals with it. E.g. If you need to allocate some memory or open up a file, You can use smart objects (smart pointer, auto_ptr, smart file handlers etc..) instead of calling new or fopen directly. When you do this, and if an exception is thrown in your constructor, the smart objects will automatically release the resources it acquired, as the stack unwinds. If you do not use the “resource allocation is initialization” technique, the user will need to wrap the statements in try/catch block and rethrow after cleaning up the mess, something like what the finally block does in Java or C#. Although this works in theory, it’s up to the user to make this work and it also always a source of errors and bugs (esp. memory and handle leaks) and is messy

As you have seen, there is no “one size fits all” rule to do error/exception handling in constructors. I have listed the most commonly used methods and one of these should work most of the time.

Posted in C++, General, Progamming Languages | 9 Comments »

Swapping variables without additional space

Posted by tekpool on December 3, 2006

Swapping variables is a very common operation used it tons of algorithms like sorting etc. The most common and obvious technique is using of a temporary variable to swap values between two variables

void swap(int &i, int &j)
   int temp = i;
   i = j;
   j = temp;

Instead of writing a separate function for each data type, you could write a MACRO or templatize the function.

Swapping without using a temporary variable is an age old trick and there are a few ways to do this. You could use of the basic arithmetic operations like +,-,/,*

1: void swap(int &i, int &j)
2: {
3:     i=i+j;
4:     j=i-j;
5:     i=i-j;
6: }

The technique involves storing the sum of variables in one of them and then extracting it back by subtracting the other number. There are different variants to this technique. E.g, instead of starting by storing the sum, you could store the difference, product or the quotient. The last two could lead you to round-off and integer division errors. However all of them have one fundamental flaw. Its in line 3, and the issue is that this could lead to an overflow error.

This is another technique the gets you around these issues; the XOR Swapping technique

void swap(int &i, int &j)
     i = i ^ j;
     j = j ^ i;
     i = i ^ j;

This is an elegant technique and should work well with any primitive data type and you could write a simple MACRO like

#define SWAP(i, j) (((i) ^= (j)), ((j) ^= (i)), ((i) ^= (j)))

Although, the XOR technique gets rid of the other issues like overflow and round off errors that we encountered in the previous technique, the lands in into yet another issues; This does not work when you try to swap the same memory location. However if can get around this by a simple ‘if’ check or a more elegant OR check like

#define SWAP(i, j) ( (i==j) || ((i) ^= (j)), ((j) ^= (i)), ((i) ^= (j)))

The first OR condition (i == j) is checked before the actual SWAP. (You do not need a SWAP if the both memory locations hold the same data)

Posted in Algorithms, Bit Fiddling, C++, General | 7 Comments »