2: Using Classes and Inheritance

Win32++

Tutorials

Menu of tutorials

Tutorial 1:   The Simplest WindowTutorial 2:   Using Classes and Inheritance
Tutorial 3:   Using Messages to Create a Scribble Window
Tutorial 4:   Repainting the Window
Tutorial 5:   Wrapping a Frame around our Scribble Window
Tutorial 6:   Customising Window Creation
Tutorial 7:   Customising the ToolBar
Tutorial 8:   Loading and Saving Files
Tutorial 9:   Printing
Tutorial 10: Finishing Touches

Tutorial 2:  Using Classes and Inheritance

The program in the previous tutorial calls the CWinApp class directly.  Normally, however, we would inherit from this class to have more control over the type of  CWinApp objects we create.

This is an example of how we would derive a class from CWinApp.

// A class that inherits from CWinApp. 
// It is used to run the application's message loop.
class CSimpleApp : public CWinApp
{
public:
    CSimpleApp() {}
    virtual ~CSimpleApp() {}
    virtual BOOL InitInstance();

private:
    CView m_View;
};

BOOL CSimpleApp::InitInstance()
{
    // Create the Window
    m_View.Create();

    return TRUE;
}

Notice that we override InitInstance to determine what happens when the application is started. In this instance we create the window for the m_View member variable. The m_View member variable is a CView object inherited from CWnd. The code for CView is shown below.

//  * Add the Win32++\include  directory to project's additional include directories

#include "wincore.h"


// A class that inherits from CWnd. It is used to create the window.
class CView : public CWnd
{
public:
    CView() {}
    virtual void OnDestroy() { PostQuitMessage(0); } // Ends the program
    virtual ~CView() {}
};

The CSimpleApp and CView classes are used in WinMain as follows.

int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
    // Start Win32++
    CSimpleApp MyApp;

    // Run the application
    return MyApp.Run();
}

The source code for this tutorial is located within the Tutorial folder of the software available from SourceForge at http://sourceforge.net/projects/win32-framework.