Sep 162013
 

C++ Technical Interview Question

Is there a bug in the following C++ code snippet?

class Base
{
public:
	Base()
		: m_pBaseIds(new int[200])
	{
	}

	virtual ~Base() { DelPtrs(); }

protected:
	virtual void DelPtrs()
	{
		delete [] m_pBaseIds;
	}

private:
	int* m_pBaseIds;
};

class Derived : public Base
{
public:
	Derived() 
		: m_pIds(new int[100])
	{

	}

protected:
	virtual void DelPtrs()
	{
		delete [] m_pIds;
		__super::DelPtrs();
	}

private:
	int* m_pIds;
};

I’ll post my answer in a while once interested people post some answers. This is a pretty easy one for experts but a real good one to check OO basics of C++ candidates.

My Answer

Yes there is a bug. Its a memory leak, be aware that a virtual function call from a constructor/destructor will not behave as expected. The call will not call the implementation in the derived class. You’ll not get an error message either. You’ll take notice of the bug only until the memory starts growing, god forbid this happens in production environment. You’ll end up having to call me up. :) The correct way to fix such issues is to use the C++ STL classes or the equivalent language collection classes to avoid direct memory allocation. The other and probably the ideal way to fix this issue is to let the allocator be the de-allocator. So if derived is allocating then let derived do de-allocation.

Mar 262009
 

There are two functions which helps in capturing mouse input, it’s called SetCapture and ReleaseCapture and a helper function called GetCapture which returns a handle to the capture window associated with the current thread. If no window in the thread has captured the mouse, the return value is NULL.

Why do we need to capture mouse?

An example is when doing rubber band drawing. If mouse goes out of our window we won’t be able to get mouse movement events, but with a call to SetCapture this will be possible as a result our line keeps moving vertically and horizontally according to mouse movement. Ideal flow for drawing rubber band lines should be…

  1. OnLButtonDown – Capture mouse using SetCapture
  2. OnMouseMove – We’ll continue drawing rubber band lines, also clear previous line.
  3. OnLButtonUp – Release mouse using ReleaseCapture
  4. Neatly handle WM_CAPTURECHANGED just in case in someone captures mouse in between the drawing process.

Some points to note…

  1. Only one window at a time can capture mouse input.
  2. Only the foreground window can capture mouse input.
  3. Background windows can capture mouse input but they’ll receive mouse notifications only when mouse moves over their visible region.
  4. Menu hotkeys and accelerators don’t work when mouse is captured.

Don’t forget to handle WM_CAPTURECHANGED message, because if another window calls SetCapture then this message is fired to the window that is losing mouse capture. To release captured mouse call ReleaseCapture.