CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

MFC – Convert C++ Class to MFC based class

Microsoft Foundation Classes (MFC) are used to develop Windows based applications. MFC supports Document-View architecture; where data management separates from presentation layer. MFC wraps portions of Windows API C++ classes and enables to use them easily.

In this article, we will discuss how to enable MFC to a simple C++ class.

Let’s take a simple example:

// Shape.cpp
//
#include <iostream>

using namespace std;

class Shape
{
public:
	Shape()
	{
		cout << "This is a Shape class." << endl;
	}
};

void main()
{
	Shape shape;
}

This is a Shape class. Just it displays “This is a Shape class.” text when we create an instance of it.

Let’s enable MFC to Shape class.

We need to derive Shape class from CObject. Almost every class in MFC is derived from its parent class CObject. In order to enable normal C++ class to MFC class, we must derive the normal C++ class from MFC’s CObject class.

We will separate declaration part into C++ header file (Shape.h file) and keep the implementation part into code file (Shape.cpp file).

Add the necessary header files to enable MFC. Include these header files into Shape.h file.

#include <afx.h>

The code will looks like below.

Shape.h header file.

// Shape.h
//
#include <afx.h>
#include <iostream>

class Shape : public CObject
{
public:
	Shape();
};

Shape.cpp implementation file.

// Shape.cpp
//
#include "Shape.h"

using namespace std;

Shape::Shape()
{
	cout << "This is a Shape class." << endl;
}

// -- main()
//
void main()
{
	Shape shape;
}

Now compile Shape.cpp file. Below is the command. Type this command at command prompt. Ignore if any warnings occurred.

cl Shape.cpp /EHsc

After compilation, it will generate Shape.exe file. Once you run it, it will display “This is a Shape class.” message on console window.

MFC is enabled to Shape class. Now you can use any of the MFC’s classes inside Shape class.

**

MFC – Convert C++ Class to MFC based class

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top
Exit mobile version