Monthly Archives: January 2007

Terms: Superclass vs. Subclass

From "ATL Internals: Working with ATL 8, Second Edition".


The Windows object model of declaring a window class and creating instances of that class is similar to that of the C++ object model. The WNDCLASSEX structure is to an HWND as a C++ class declaration is to a this pointer. Extending this analogy, Windows superclassing[3] is like C++ inheritance. Superclassing is a technique in which the WNDCLASSEX structure for an existing window class is duplicated and given its own name and its own WndProc. When a message is received for that window, it’s routed to the new WndProc. If that WndProc decides not the handle that message fully, instead of being routed to DefWindowProc, the message is routed to the original WndProc. If you think of the original WndProc as a virtual function, the superclassing window overrides the WndProc and decides on a message-by-message basis whether to let the base class handle the message.

[3] The theory of Windows superclassing is beyond the scope of this book. For a more in-depth discussion, see Win32 Programming (Addison-Wesley, 1997), by Brent Rector and Joe Newcomer.

The reason to use superclassing is the same reason to use inheritance of implementation: The base class has some functionality that the deriving class wants to extend. ATL supports superclassing via the DECLARE_WND_SUPERCLASS macro.



Previously in this chapter, I described superclassing as the Windows version of inheritance for window classes. Subclassing is a more modest and frequently used technique. Instead of creating a whole new window class, with subclassing, we merely hijack the messages of a single window. Subclassing is accomplished by creating a window of a certain class and replacing its WndProc with our own using SetWindowLong(GWL_WNDPROC). The replacement WndProc gets all the messages first and can decide whether to let the original WndProc handle it as well. If you think of superclassing as specialization of a class, subclassing is specialization of a single instance. Subclassing is usually performed on child windows, such as an edit box that the dialog wants to restrict to letters only. The dialog would subclass the child edit control during WM_INITDIALOG and handle WM_CHAR messages, throwing out any that weren’t suitable.

[11] For a more complete dissection of Windows subclassing, see Win32 Programming (Addison-Wesley, 1997), by Brent Rector and Joe Newcomer.