Tuesday, March 3, 2015

Singleton pattern design and implementation

Singleton pattern is a design pattern that restricts the instantiate of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. 

One way of creating Singleton using Mutex

"A Mutex is essentially the same thing as a binary semaphore and sometimes uses the same basic implementation. The differences between them are in how they are used. While a binary semaphore may be used as a Mutex , a Mutex is a more specific use-case, which allows extra guarantees:"

Properties of Mutex:

  • Mutexes have a concept of an owner. Only the process that locked the Mutexis supposed to unlock it. If the owner is stored by the Mutexthis can be verified at runtime.
  • Mutexes may provide priority inversion safety. If the Mutexknows its current owner, it is possible to promote the priority of the owner whenever a higher-priority task starts waiting on the Mutex.
  • Mutexes may also provide deletion safety, where the process holding the Mutexcannot be accidentally deleted.
MFC implementation of Singleton using Mutex

  1.  Add a header file named LimitSingleInstance.h to the project.
  2. Add the following code in  LimitSingleInstance.h

#ifndef LimitSingleInstance_H
#define LimitSingleInstance_H

#include  

//This code is from Q243953 in case you lose the article and wonder
//where this code came from.
class CLimitSingleInstance
{
protected:
  DWORD  m_dwLastError;
  HANDLE m_hMutex;

public:
  CLimitSingleInstance(TCHAR *strMutexName)
  {
    //Make sure that you use a name that is unique for this application otherwise
    //two apps may think they are the same if they are using same name for
    //3rd parm to CreateMutex
    m_hMutex = CreateMutex(NULL, FALSE, strMutexName); //do early
    m_dwLastError = GetLastError(); //save for use later...
  }
   
  ~CLimitSingleInstance() 
  {
    if (m_hMutex)  //Do not forget to close handles.
    {
       CloseHandle(m_hMutex); //Do as late as possible.
       m_hMutex = NULL; //Good habit to be in.
    }
  }

  BOOL IsAnotherInstanceRunning() 
  {
    return (ERROR_ALREADY_EXISTS == m_dwLastError);
  }
};
#endif

3. In the application class InitInstance() method add the following code


CLimitSingleInstance g_SingleInstanceObj(TEXT("Global\\{AD3DB0CB-8197-4C9F-A425-40C75309A7D0}"));
BOOL CSingleTonApp::InitInstance()
{
if(g_SingleInstanceObj.IsAnotherInstanceRunning()){
AfxMessageBox(_T("Another Instance is Running"));
return FALSE;
}
//..... do something 
//.....
return TRUE;
}



4. The GUID value can be generated by using Tools Menu >> Create GUID >> Registry Format.

5. Now, only one application object instantiates for the Windows application class. So, there will be only instance of the application.
-

Monday, March 2, 2015

C++, VC++ and MFC interview questions.

1.) How many constructor can a class have?

A class can have any number of constructors. However after creating a constructor explicitly the default constructor becomes invalid for that class. We will need to define a constructor with zero argument explicitly.


2.)What is the difference class and structure?

The main difference between structure and class is that members in structure is public by default where as members in class is private by default.

3.) What is Singleton class?

Singleton class is required when only one object of a class needs to be created throughout the life of the program.

example:
#include
using namespace std;

class Singleton
{
private:
static bool bInstanceflag;
static Singleton *pSingle;
Singleton()
{
private constructor
}

public:
void method();
static Singleton* GetInstance();
}

bool Singleton::bInstanceflag = false;
static Singleton::pSingle = FALSE;
Singleton* Singleton::GetInstance()
{
if(!bInstancefalg)
{
pSingle = new Singleton;
bInstanceflag = true;
return pSingle;
}
else
{
return pSingle;
}
}


void main()
{

}

4.)  What is base class of MFC Library?

CObject is the base class for the Microsoft Foundation Class Library. At most 80% of MFC classes are derived from CObject.

CObject provides

– Serialization support
– Run-time class information
– Object diagnostic output
– Compatibility with collection classes

CObject does not support multiple inheritance. Your derived classes can have only one CObject base class, and that CObject must be leftmost in the hierarchy. It is permissible, however, to have structures and non-CObject-derived classes in right-hand multiple-inheritance branches.
You will realize major benefits from CObject derivation if you use some of the optional macros in your class implementation and declarations.

The first-level macros, DECLARE_DYNAMIC and IMPLEMENT_DYNAMIC, permit run-time access to the class name and its position in the hierarchy. This, in turn, allows meaningful diagnostic dumping.

The second-level macros, DECLARE_SERIAL and IMPLEMENT_SERIAL, include all the functionality of the first-level macros, and they enable an object to be "serialized" to and from an "archive."

For information about deriving Microsoft Foundation classes and C++ classes in general and using CObject, see Using CObject and Serialization.

5.) What is the Difference between ASSERT and VERIFY?

ASSERT evaluates the expression only in the debug version and will throw an exception if the result is 0 and the program termintes.
VERIFY evalutes the expression in Debug and Release version also and if the result is 0, will throw an exception only in Debug mode.

6.) Difference between PostMessage and SendMessage?

The PostMessage function places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message.

The SendMessage function sends the specified message to a window or windows. It calls the window procedure for the specified window and does not return until the window procedure has processed the message.

7.) What is the difference between PeekMessage and GetMessage?

We can use the PeekMessage function to examine a message queue during a lengthy operation. PeekMessage is similar to the GetMessage function, both check a message queue for a message that matches the filter criteria and then copy the message to an MSG structure. The main difference between the two functions is that GetMessage does not return until a message matching the filter criteria is placed in the queue, whereas PeekMessage returns immediately regardless of whether a message is in the queue.


8.) Difference between Modal and Modeless Dialog?

Modal dialog box captures the message loop, whereas model less does not. Call DoModal to create the dialog window and its controls for a modal dialog. If you wish to create a modeless dialog, call Create in the constructor of your Cdialog class.


9.) What is the use of the class CCmdTarget?

It is the base class for the MFC library message map architecture. Which maps commands/messages to the member functions to handle them. Classes derived from this are CWnd,CWinApp,CFrameWnd,CView, CDocument

10.) What is the difference between hInstance and hWnd?

hWnd is the window’s handle and is how the OS defines a window when talking about it inside the PC.
hInstance is the OS’s handle for the program when running it.


11.) What is the difference between hinsrtance and hprevinstance in WinMain function?

hInstance used to have the handle of the current instance

hPrevInctance used to have the handle of last instance, hPrevInstance is NULL if only one instance is running


12.) Difference between Window’s OnPaint and View’s OnDraw overridable functions?

Window’s OnPaint function executes corresponding to each WM_PAINT messages. But in the case of document-view architecture when a view receives a WM_PAINT message, it invokes view’s OnDraw function. Actually the framework fields the WM_PAINT message, creates a CPaintDC object, and calls the view’s OnDraw function with a pointer to the CPaintDC object.

The fact that the view doesn’t have to construct its own device context object is a minor convenience. The real reason the framework uses OnDraw is so that the same code can be used for output to a window, for printing, and for print previewing. When a WM_PAINT message arrives, the framework passes the view a pointer to a screen device context so that output will go to the window. When a document is printed, the framework calls the same OnDraw function and passes it a pointer to a printer device context.

13.) Command routing in MFC?

One of the most remarkable features of the document/view architecture is that an application can handle command messages almost anywhere. Command messages is MFC’s term for the WM_COMMAND messages that are generated when items are selected from menus, keyboard accelerators are pressed, and toolbar buttons are clicked. The frame window is the physical recipient of most command messages, but command messages can be handled in the view class, the document class, or even the application class by simply including entries for the messages you want to handle in the class’s message map. The flow of command messages from Active View to DefWindowProc is know as command routine.



14.) How Message Map works in an MFC application?

The message map functionality in an MFC application works by the support of 3 Macros, DECLARE_MESSAGE_MAP, BEGIN_MESSAGE_MAP, and END_MESSAGE_MAP and the WindowProc function implementation.

MFC’s DECLARE_MESSAGE_MAP macro adds three members to the class declaration: a private array of AFX_MSGMAP_ENTRY structures named _messageEntries that contains information correlating messages and message handlers; a static AFX_MSGMAP structure named messageMap that contains a pointer to the class’s _messageEntries array and a pointer to the base class’s messageMap structure; and a virtual function named GetMessageMap that returns messageMap’s address. BEGIN_MESSAGE_MAP contains the implementation for the GetMessageMap function and code to initialize the messageMap structure. The macros that appear between BEGIN_MESSAGE_MAP and END_MESSAGE_MAP fill in the _messageEntries array, and END_MESSAGE_MAP marks the end of the array with a NULL entry.

Thus corresponding to each message a class can traverse through it’s and base classes message map entries to find a handler till it to reach the DefWindowProc.

15.) What is the difference between thread and process?

In the Microsoft Win32 environment, every running application constitutes a process and every process contains one or more threads of execution. A thread is a path of execution through a program’s code, plus a set of resources (stack, register state, and so on) assigned by the operating system.

MFC OnPaint() vs OnDraw()

The two are more or less the same. OnPaint is the handler for a WM_PAINT message. OnDraw is the function that a MFC CView window calls when it receives a WM_PAINT message. 

We should use OnDraw if the window is derived from CView, otherwise OnPaint.


OnDraw()
OnPaint()
A member function of CView.

OnDraw is a virtual function. 

OnPaint handler for views call a virtual function OnDraw.

CView::OnDraw

virtual void OnDraw( 
   CDC* pDC  
) = 0

pDC
Points to the device context to be used for rendering an image of the document.


A member function of CWnd.

OnPaint is a WM_PAINT message handler.

CWnd::OnPaint

afx_msg void OnPaint( );

Common operators to overload


Assignment Operator

X& X::operator=(X rhs) { swap(rhs); return *this; }



Bitshift Operators (used for Stream I/O)

The bitshift operators << and >>, although still used in hardware interfacing for the bit-manipulation functions they inherit from C, have become more prevalent as overloaded stream input and output operators in most applications. For guidance overloading as bit-manipulation operators, see the section below on Binary Arithmetic Operators. For implementing your own custom format and parsing logic when your object is used with iostreams, continue.

The stream operators, among the most commonly overloaded operators, are binary infix operators for which the syntax specifies no restriction on whether they should be members or non-members. Since they change their left argument (they alter the stream’s state), they should, according to the rules of thumb, be implemented as members of their left operand’s type. However, their left operands are streams from the standard library, and while most of the stream output and input operators defined by the standard library are indeed defined as members of the stream classes, when you implement output and input operations for your own types, you cannot change the standard library’s stream types. That’s why you need to implement these operators for your own types as non-member functions. The canonical forms of the two are these:

std::ostream& operator<<(std::ostream& os, const T& obj) { // write obj to stream return os; } std::istream& operator>>(std::istream& is, T& obj) { // read obj from stream if( /* no valid object of T found in stream */ ) is.setstate(std::ios::failbit); return is; }

When implementing operator>>, manually setting the stream’s state is only necessary when the reading itself succeeded, but the result is not what would be expected.
Function call operator
The function call operator, used to create function objects, also known as functors, must be defined as a member function, so it always has the implicit this argument of member functions. Other than this it can be overloaded to take any number of additional arguments, including zero.
Throughout the C++ standard library, function objects are always copied. Your own function objects should therefore be cheap to copy. If a function object absolutely needs to use data which is expensive to copy, it is better to store that data elsewhere and have the function object refer to it.

Comparison operators

The binary infix comparison operators should, according to the rules of thumb, be implemented as non-member functions1. The unary prefix negation ! should (according to the same rules) be implemented as a member function. (but it is usually not a good idea to overload it.)

The standard library’s algorithms (e.g. std::sort()) and types (e.g. std::map) will always only expect operator< to be present. However, the users of your type will expect all the other operators to be present, too, so if you define operator<, be sure to follow the third fundamental rule of operator overloading and also define all the other boolean comparison operators. The canonical way to implement them is this:

inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ }

inline bool operator!=(const X& lhs, const X& rhs){return !operator==(lhs,rhs);}


inline bool operator< (const X& lhs, const X& rhs){ /* do actual comparison */ }


inline bool operator> (const X& lhs, const X& rhs){return operator< (rhs,lhs);}


inline bool operator<=(const X& lhs, const X& rhs){return !operator> (lhs,rhs);}


inline bool operator>=(const X& lhs, const X& rhs){return !operator< (lhs,rhs);}


The important thing to note here is that only two of these operators actually do anything, the others are just forwarding their arguments to either of these two to do the actual work.
The syntax for overloading the remaining binary boolean operators (||, &&) follows the rules of the comparison operators. However, it is very unlikely that you would find a reasonable use case for these2.

1 As with all rules of thumb, sometimes there might be reasons to break this one, too. If so, do not forget that the left-hand operand of the binary comparison operators, which for member functions will be *this, needs to be const, too. So a comparison operator implemented as a member function would have to have this signature:
bool operator<(const X& rhs) const { /* do actual comparison with *this */ } (Note the const at the end.)

2 It should be noted that the built-in version of || and && use shortcut semantics. While the user defined ones (because they are syntactic sugar for method calls) do not use shortcut semantics. User will expect these operators to have shortcut semantics, and their code may depend on it, Therefore it is highly advised NEVER to define them.
Arithmetic Operators

Unary arithmetic operators

The unary increment and decrement operators come in both prefix and postfix flavor. To tell one from the other, the postfix variants take an additional dummy int argument. If you overload increment or decrement, be sure to always implement both prefix and postfix versions. Here is the canonical implementation of increment, decrement follows the same rules:

class X { X& operator++() { // do actual increment return *this; } X operator++(int) { X tmp(*this); operator++(); return tmp; } };

Note that the postfix variant is implemented in terms of prefix. Also note that postfix does an extra copy.2
Overloading unary minus and plus is not very common and probably best avoided. If needed, they should probably be overloaded as member functions.

2 Also note that the postfix variant does more work and is therefore less efficient to use than the prefix variant. This is a good reason to generally prefer prefix increment over postfix increment. While compilers can usually optimize away the additional work of postfix increment for built-in types, they might not be able to do the same for user-defined types (which could be something as innocently looking as a list iterator). Once you got used to do i++, it becomes very hard to remember to do ++i instead when i is not of a built-in type (plus you'd have to change code when changing a type), so it is better to make a habit of always using prefix increment, unless postfix is explicitly needed.

Binary arithmetic operators

For the binary arithmetic operators, do not forget to obey the third basic rule operator overloading: If you provide +, also provide +=, if you provide -, do not omit -=, etc. Andrew Koenig is said to have been the first to observe that the compound assignment operators can be used as a base for their non-compound counterparts. That is, operator + is implemented in terms of +=, - is implemented in terms of -= etc.
According to our rules of thumb, + and its companions should be non-members, while their compound assignment counterparts (+= etc.), changing their left argument, should be a member. Here is the exemplary code for += and +, the other binary arithmetic operators should be implemented in the same way:

class X { X& operator+=(const X& rhs) { // actual addition of rhs to *this return *this; } }; inline X operator+(X lhs, const X& rhs) { lhs += rhs; return lhs; }

operator+= returns its result per reference, while operator+ returns a copy of its result. Of course, returning a reference is usually more efficient than returning a copy, but in the case of operator+, there is no way around the copying. When you write a + b, you expect the result to be a new value, which is why operator+ has to return a new value.3 Also note that operator+ takes its left operand by copy rather than by const reference. The reason for this is the same as the reason giving for operator= taking its argument per copy.
The bit manipulation operators ~ & | ^ << >> should be implemented in the same way as the arithmetic operators. However, (except for overloading << and >> for output and input) there are very few reasonable use cases for overloading these.

3 Again, the lesson to be taken from this is that a += b is, in general, more efficient than a + b and should be preferred if possible.

Array Subscripting

The array subscript operator is a binary operator which must be implemented as a class member. It is used for container-like types that allow access to their data elements by a key. The canonical form of providing these is this:

class X { value_type& operator[](index_type idx); const value_type& operator[](index_type idx) const; // ... };

Unless you do not want users of your class to be able to change data elements returned by operator[] (in which case you can omit the non-const variant), you should always provide both variants of the operator.If value_type is known to refer to a built-in type, the const variant of the operator should return a copy instead of a const reference.

Overloading new and delete

The C++ standard library comes with a set of predefined new and delete operators. The most important ones are these:

void* operator new(std::size_t) throw(std::bad_alloc); 
void  operator delete(void*) throw(); 
void* operator new[](std::size_t) throw(std::bad_alloc); 

void  operator delete[](void*) throw(); 

When new is overloaded, delete  must be overloaded.

When to overload new and delete?

1. To Detect Usage Errors
2. To Improve Efficiency(speed & memory)
3. To Collect Memory Usage Statistics
4. To compensate for sub optimal memory alignment
5. To obtain unconventional behavior