C++ Hard Interview Questions – part1

1. Why don’t we have virtual constructors?

The virtual mechanism, though used without the knowledge of the complete type of the object, works only on fully-constructed objects. But, in order to create an object, the user is required to provide the complete information about the object. Thus, it is not possible for a constructor to be virtual.

2. What is virtual destructor?

Consider a class “Base” that is inherited by another class “Derived” and there exists a pointer-to-base referring to a heap-allocated derived object, then a virtual destructor would be required in the base class for the proper clean-up of the object. If the destructor is not virtual, then the destructor for the derived sub-object won’t be called and hence, the resources will not be freed.

For Example:

#include<iostream>

struct Base
{
      Base(){std::cout<<"Base object constructed\n";}
      ~Base(){std::cout<<"Base object destructed\n";}
};

struct Derived: Base
{
      Derived(){std::cout<<"Derived object constructed\n";}
      ~Derived(){std::cout<<"Derived object destructed\n";}
};

int main()
{
      {
            Base b_Obj;
            Derived d_obj;
      }
      {
            Base *p_b = new Derived();
            delete p_b;
      }
}

In the above code, the b_obj and d_obj would be destructed properly but the object referred-to by the pointer p_b won’t be destructed properly until the base class’ destructor is made virtual.

This is because when p_b is delete-ed, it calls the destructor of the static type of the pointer, which is Base, instead of the Dynamic type.

Thus, whenever it is possible that your class might be inherited by another class, it is safe to make the destructor virtual.

3. What is Self-Assignment? Does it have any bugs/problems associated with it?

Assignment of an object to itself is known as self-assignment.

For example:

int func(int &x, int &y)
{
      x=x;   /* Self Assignment */

      x=y;   /* Self-Assignment, because x and y both refer to "data" [defined in main() ] */
}

int main()
{
      int data=10;
      fun(data, data);
}

One potential problem associated with self-assignment arises in the following code:

class dummy
{
      int n;
      int *ptr;

public:
      dummy() : ptr(new int){ *ptr = 0; }
      ~dummy() {delete ptr;}

      dummy& operator= (const dummy& D)
      {
            delete ptr; /* #1 */
            ptr= D.ptr; /* #2 */
      }

      int* operator*()
      {
            return ptr;
      }
};

int main()
{
      dummy mObj(10);
      mObj = mObj;
}

Here, Line #1, delete-s the pointer ptr, which is then invalidated. Line #2 assigns that freed memory back to ptr. If the pointer is now used, it will invoke Undefined Behavior.

To prevent this, the = operator should first check for self-assignment.

dummy& operator= (const dummy& D)
{
      if(*this==D)
            return *this;
      else
      {
            delete ptr;
            ptr = D.ptr;
            return *this;
      }
}


4. What do you mean by Shallow copy and Deep copy?

Shallow copy and Deep copy are two ways of copying an object.
Consider the following code

class Dummy
{
      string d_str;
      int* d_ptr;
public:
      Dummy(string xstr, int* dptr) : d_str(xstr), d_ptr(pstr) {}
      ~Dummy() { delete d_ptr;}
};

int main()
{
      Dummy Xobj("Test_Object", new int);
      {
            Dummy Yobj = Xobj;
      }
}

A shallow copy of an object copies it bit-by-bit. This is what happens in the implicitly-defined assignment operator and copy constructor.

In the above example, the Xobj will be copied bit-by-bit into Yobj. Here, the copy constructor of Xobj.d_str will be first invoked to copy its contents into Yobj.d_str and then the Xobj.d_ptr would be copied  into Yobj.d_str and Yobj.d_ptr. The copy constructor of std::string has been defined to perform a Deep copy but the Xobj.d_ptr would be shallow-copied which means that Xobj.d_ptr and Yobj.d_ptr will both point to the same memory location and any change to one pointer will cause a change to the other.

The main problem occurs when an object goes out of scope or a pointer element is freed/invalidated. In the above example, Yobj will go out of scope and the memory pointed would be freed, causing both Xobj.d_ptr and Yobj.d_ptr to be invalidated and, thus, the user is not allowed to use Xobj.d_ptr any further.

A deep copy of Xobj into Yobj would cause the member Yobj.d_ptr to get hold of a new memory location and the contents of the memory be same as of those referred by the member Xobj.d_ptr. Now, as the memory location referred by Xobj.d_ptr and that by Yobj.d_ptr are different, deletion/invalidation of the memory causes no trouble to Xobj.

5. What is the Placement new? Where would you use it? What are your responsibilities?

The Placement new operator is used in case you want the object to be placed at a particular pre-allocated memory.

For Example:

class test
{
      /* members and methods */
};

int main()
{
      char memory[sizeof(test)];
      char* position = memory;
      test* object = new(position) test;
}

Some situations where placement new can be used are :

  1. When writing your memory allocation unit and you want memory to be allocated from only a pre-allocated section of memory.
  2. Used when it is required that I/O devices be mapped to specific memory addresses.
  3. To create a shared memory region (for Inter-process Communication)

There are a lot of other uses of placement new. Check here

When using placement new, the following points need to be kept in mind:

  1. Don’t use placement new unless you really need it and it is important that the object be places at some particular location in memory
  2. It is the programmer’s job to check that the memory being used has enough space for the object and the memory is aligned properly.
  3. The programmer is responsible for destruction the placed object, i.e., the programmer needs to call the destructor explicitly.

About the Author:  Saurabh Manchanda is a whiz C/C++ programmer. He is currently pursuing his Bachelors of Technology degree in Computer Science. His passions are programming, studying algorithms and solving puzzles. He loves reading books, technical textbooks and fiction novels. When not programming, he could be seen playing pool or cricket or watching movies, listening to songs or staring at his pet fishes! You can connect him at Orkut, Facebook, follow him on Twitter or contact him at saurabh29789@gmail.com If you are thankful for his posts, you may want to gift an item from his Amazon Wish List.



All comments of post - "C++ Hard Interview Questions – part1":

:Haha! I'am the first! Yeh~

Thank you!

Add a Comment / Trackback url

  1. #1  MimiNo Gravatar

    Those questions are not especially hard..

    10/06/25 21:43

Show all Show 5 so far Close all

Comment begin from here or jump up!