14.10 Using Member Variables Instead of cbWndExtra Bytes

Windows provides a mechanism by which an arbitrary number of extra bytes can be attached to each window of a particular class. Programmers typically use these extra bytes to store extra information about the window or the data displayed by the window.

In a traditional Windows program, you specify the number of extra bytes for a particular window class in the cbWndExtra field of the WNDCLASS structure, which is used when you call RegisterClass to create the Windows registration class. For each window of that registration class that you create, Windows allocates the specified number of extra bytes for the window structure. The bytes are

accessed as an untyped array of bytes with the GetWindowLong and SetWindowLong functions. These bytes are allocated in the USER's heap, which is a limited Windows resource used by all running Windows applications.

In a Windows program based on the Microsoft Foundation Class Library, you seldom call RegisterClass. Instead, you derive a new window class from an existing Foundation window class using the C++ derivation mechanism.

If you need extra data attached to each window that you have created from a derived class, you can simply add member variables to the class declaration when you derive the class. You can then use normal C++ syntax to access these member variables for each window object that you create.

Access to these member variables has the advantage of being type-safe, as opposed to the untyped array-of-bytes method used in traditional Windows programs. In addition, the member variables are allocated in the program's data segment, which is not as precious as the USER heap.

·To use member variables to add extra bytes:

Declare the member variables to hold window-specific data and then access those members:

class CMyWnd : public CFrameWnd

{

public:

// window-specific extra data

char* m_FileName;

long m_cbChars;

BOOL m_isDirty;

int m_topLineDisplayed;

// other class declaration stuff ...

};

CMyWnd* myWindow = new CMyWnd( ... );

if( myWindow->m_cbChars > MAX_SIZE )

//...