Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

.NET

Multiple Inheritance for MFC 4.0


JAN96: Multiple Inheritance for MFC 4.0

Jean-Louis currently works for a small marketing company. He can be reached at [email protected].


The recently released Microsoft Foundation Class library Version 4.0 incorporates features such as full encapsulation of Windows 95 controls, the ability to create and use OLE controls, and a database-access model called "Data Access Objects." One thing MFC 4.0 doesn't support, however, is multiple inheritance. In fact, Microsoft's MFC Tech Note #16 even attempts to dissuade you from using it. For instance, in discussing multiple inheritance, Tech Note #16 points out that CObject can appear only once in the inheritance graph of your class--and CObject-derived classes can only appear on the left-most edges of the graph. This splits the app's classes into two categories: those that inherit from CObject (and receive full service from the framework) and those that MFC ignores.

While this may be Microsoft's choice, it does not necessarily have to be yours. After all, many people (including Bjarne Stroustrup) believe that multiple inheritance can be useful. While I won't attempt to convince you of the value of multiple inheritance in this article, I will show how you can lift some of Tech Note #16's restrictions without hacking the MFC source or loosing functionality.

A Peek at MFC 4.0

The last "public" release of MFC was 3.0. Since that time, subscribers to the Microsoft Developer Network have seen incremental changes in MFC that add support for Windows Sockets, Simple MAPI, and Windows 95 common controls. MFC 4.0 brings other features to the table, raising the total number of classes to just over 150.

For example, MFC 4.0 provides support for multithreaded programming through a new base class, CSyncObject. Under this base class are a collection of derived classes to handle semaphores, mutexes, synchronization, events, and the like. Support for OLE is provided through an OLE container that allows you to create an OLE control. OLE controls are treated as special child windows and associated with a parent window through CWnd. Thus, you can create an instance of a control using CWnd::CreateControl. MFC also adds two new OLE common dialog classes, CPageSetupDialog and COlePropertiesDialog, to encapsulate the Page Setup dialog box and OLE Properties dialog box, respectively.

A lot of work has gone into some of the less "visual" portions of the framework. CArchive, for example, is no longer limited to 32 K objects, and now uses the class-specific new operator if there is one. CStrings use (at last!) reference counting to greatly reduce the cost of passing or returning a string by value. Also, redefinition of new as DEBUG_NEW (a debugging technique promoted by Microsoft) no longer breaks the IMPLEMENT_SERIAL and IMPLEMENT_DYNCREATE macros.

Supporting Multiple Inheritance

MFC belongs to the category of tree-like frameworks, like the NIH class library or Borland's OWL 1.0. MFC, however, differs in its support of multiple inheritance. The NIH class library, for instance, can be compiled with support for multiple inheritance by making the root Object class a virtual base class. This approach, however, is dismissed by Tech Note #16. The real problem with virtual inheritance of CObject, however, is that it breaks some parts of MFC.

It turns out that MFC 4.0 is almost capable of dealing with virtual CObjects. If you attempt to write and use a class that virtually inherits from CObject, two problems can arise. The first one occurs only if the object is serializable and is detected by the compiler. The IMPLEMENT_SERIAL macro will then trigger an "error: downcast involving a virtual base class" message. Among other things, IMPLEMENT_SERIAL generates the extraction operator >>, which reads the next CObject from a CArchive, checks its class, and casts the pointer to the requested type. Since MFC uses a static cast, IMPLEMENT_SERIAL will not compile if CObject is virtually inherited. This is easy to fix. Visual C++ 4.0 supports new cast operators such as dynamic_cast<>. To make serialization work again you need a VIMPLEMENT_SERIAL that uses dynamic_cast<> instead of the old cast notation; see Listing One. This is, by the way, a good opportunity to fill a gap in MFC: VIMPLEMENT_SERIAL and VDECLARE_SERIAL make it possible to deserialize a pointer to a const object.

The second problem with virtually inheriting from CObject is more difficult to remedy because it occurs only in debug builds, and the compiler won't warn you. The program will build and run until functions such as CMemoryState::DumpAllObjectsSince() are called, either explicitly or when the program terminates and MFC attempts to dump leaked objects.

At this point, a description of the dump process is necessary. Starting with Visual C++ 4.0, the C run-time library (CRT) also exists in debug version. A header file crtdbg.h declares various interfaces to heap diagnostics. You can use them to monitor heap activity, visit each allocation, get statistics on heap usage, report memory leaks, and the like. All of this should sound familiar. Indeed, these functions were previously part of MFC. Moving them to the CRT solves several problems. For example, you can now use the heap diagnostics even if your application isn't MFC based--even if it's written in plain old C. The debug versions of heap functions (_malloc_dbg, _realloc_dbg, and so on) have extra parameters that associate a source filename and line number with an allocation. They also require a type parameter: normal, client, ignore, or CRT. Only nodes of the first two categories appear in heap dumps.

ignore blocks are useful when memory needs to be allocated, but the allocation pattern differs between runs of the same program. An example is the temporary CWnd objects allocated by MFC in response to various Windows events. Having them in the way would make it impossible to troubleshoot heap problems. CRT blocks are allocated by the library for internal use. For example, the iostream library needs to allocate buffers as part of its initialization. Previously, these buffers were reported as memory leaks if the program also used MFC. MFC 4.0 solves this by marking the buffers as CRT blocks.

normal blocks are dumped in terms of address and size, along with a hex dump of the first few bytes. client blocks are dumped by the CRT the same way as normal blocks, but you can override this behavior by specifying a dump function that will be called by the CRT for client blocks. Listing Five is a C program that illustrates these features.

MFC sets up a client dump function. From MFC's point of view, a client block contains a CObject. Custom versions of operator new() in CObject allocate the memory as client. When the block must be dumped, MFC casts the base address of the block to CObject* and, depending on the dump context's depth, either lists the object's class obtained by a call to GetRuntimeClass() or calls the object's Dump() method. This is the source of MFC's allergy to virtually inherited CObjects. Objects are registered as client blocks, but the CObject part is floating somewhere in the block, not at the start where MFC expects it. Thus, calling virtual functions results in a crash.

There is an easy solution--override the derived class's operator new() and make it use the global operator new() instead of CObject's. The memory block will be registered as nonclient, and MFC won't later attempt to call virtual functions on it. Of course, the drawback is that the object will be dumped in hexadecimal. In other words, objects using virtual inheritance will receive only second-class support form the framework.

Fortunately, there is a better solution. Since MFC wants a CObject at the beginning of a client block, you can include an extra CObject at the beginning of the block that will act as a proxy for the actual object. Actually, you need two proxy classes--one for blocks awaiting construction, and another for blocks that contain a fully constructed, dumpable object. The sole purpose of the second proxy class is to delegate functions such as Dump(), GetRuntimeClass(), and AssertValid() to the actual object.

Listing Two, class CVirtualObject, implements this concept. A class can be virtually derived from CVirtualObject, or from any class that inherits from CVirtualObject. In release builds, CVirtualObject does nothing different from CObject. It could just as well be a typedef. In debug builds, however, CVirtualObject replaces CObject's memory management. One of the new operators is used to construct an object at a specific address; see Listing Three. It is of no interest to us and is simply passed down to CObject. The other two allocate enough memory for the object and a CBlockProxy by calling the corresponding CObject::operator new, create the proxy at the beginning of the block, and add it to a linked list of blocks for yet-to-be-constructed objects. The proxy remembers the size of the allocated memory block. The new operators then return the address of the first byte past the proxy.

The constructor of CVirtualObject calls CBlockProxy::Resolve (Listing Four), which searches the list of blocks waiting for construction. If the object under construction is found in the list, the CBlockProxy is replaced with a CObjectProxy. Of course, the two proxies must be of the same size. The address of the CObject subobject (passed from the constructor) is stored in the proxy. Note that the object can be absent from the list. For example, CVirtualObject member variables will not be found in the list. Also, a list is needed as opposed to a mere static variable because, in expressions such as new A(new B), the two calls to new take place before the execution of the constructors. The CObjectProxy simply delegates diagnostic functions to the actual object. GetRuntimeClass() is also delegated because, when the dump context's depth is equal to zero, the framework simply outputs the object's class. Finally, a delete operator is needed in CVirtualObject because the base address of the object is no longer the base address of the allocated block.

CVirtualObject won't help you virtually inherit from CDocument, but the same technique could probably be used to build a CVirtualDocument class. It can also be applied to problems not related to multiple inheritance; for example, to make MFC diagnostics work with classes not derived from CObject (and perhaps coming from another vendor). In such case, CVirtualObject could be turned into a template.

Conclusion

MFC 4.0's cleaner design makes it possible to add many extensions to the framework. However, it seems amazing that it is possible to reintroduce support for multiple inheritance in a framework designed by people who overtly contest the value of the feature. The code presented in this article allows you to do just that.

For More Information

MFC 4.0

Microsoft Corp.

One Microsoft Way

Redmond, WA 98052

206-880-8080

Listing One

# define _VDECLARE_DESERIALIZER(class_name) \
friend CArchive& AFXAPI operator>>(CArchive& ar, class_name* &pOb); \
friend CArchive& AFXAPI operator>>(CArchive& ar, const class_name* &pOb) \
    { return ar >> const_cast<class_name*&>(pOb); }
# define _VIMPLEMENT_DESERIALIZER(class_name) \
CArchive& AFXAPI operator>>(CArchive& ar, class_name*&p) { \
    CObject* pOb = ar.ReadObject(NULL); \
    if (!pOb) p = NULL; \
    else if (!(p = dynamic_cast<class_name*>(pOb)))\
    AfxThrowArchiveException(CArchiveException::badClass); \
    return ar; }
# define VDECLARE_ABSTRACT_SERIAL(class_name) \
DECLARE_DYNAMIC(class_name) \
_VDECLARE_DESERIALIZER(class_name)
# define VIMPLEMENT_ABSTRACT_SERIAL(class_name, base_class_name) \
IMPLEMENT_DYNAMIC(class_name, base_class_name) \
_VIMPLEMENT_DESERIALIZER(class_name)
# define VDECLARE_SERIAL(class_name) \
DECLARE_DYNCREATE(class_name) \
_VDECLARE_DESERIALIZER(class_name)
# define VIMPLEMENT_SERIAL(class_name, base_class_name, wSchema) \
CObject* PASCAL class_name::CreateObject() \
    { return new class_name; } \
_IMPLEMENT_RUNTIMECLASS(class_name, base_class_name, wSchema, \
    class_name::CreateObject) \
_VIMPLEMENT_DESERIALIZER(class_name)

Listing Two

# ifdef _DEBUG
class CVirtualObject : public CObject
    {
    public:
        CVirtualObject();
        void* PASCAL operator new(size_t, void* p);
        void* PASCAL operator new(size_t size);
        void* PASCAL operator new(size_t size, LPCSTR file, int line);
        void PASCAL operator delete(void* p);
        static void AfxDoForAllObjects(void (*pfn)(CObject* pObject, 
            void* pContext), void* pContext);
    };
class CProxy : public CObject
    {
    protected:
        size_t size;
        union
            {
            CBlockProxy* next;
            CVirtualObject* object;
            };
    };
class CBlockProxy : public CProxy
    {
    public:
        CBlockProxy(size_t size);
        virtual void Dump(CDumpContext& dc) const;
        static void Resolve(CVirtualObject* p);
    private:
        static CBlockProxy* head;
    };
class CObjectProxy : public CProxy
    {
    public:
        CObjectProxy(CVirtualObject* p);
        virtual void Dump(CDumpContext& dc) const;
        virtual void AssertValid() const;
        virtual CRuntimeClass* GetRuntimeClass() const;
    };
# else
class CVirtualObject : public CObject { };
# endif

Listing Three

void* PASCAL CVirtualObject::operator new(size_t size, LPCSTR file, int line)
    {
    // allocate requested memory + space for header
    void* p = CObject::operator new(size + sizeof CProxy, file, line);
    // construct a dumpable object at start of block
    new (p) CBlockProxy(size);
    // return address of first byte past header
    return reinterpret_cast<CBlockProxy*>(p) + 1;
    }

Listing Four

CVirtualObject::CVirtualObject()
    {
    // object is now constructed & dumpable
    CBlockProxy::Resolve(this);
    }
void CBlockProxy::Resolve(CVirtualObject* p)
    {
    for (CBlockProxy **pn = &head, *node; node = *pn; pn = &node->next)
            if (reinterpret_cast<BYTE*>(node + 1) <= reinterpret_cast<BYTE*>(p)
            && reinterpret_cast<BYTE*>(p) < reinterpret_cast<BYTE*>(node + 1) 
                                                                  + node->size)
            {
            // object found; remove from unconstructed block list
            *pn = node->next;
            // destroy unconstructed block header
            node->~CBlockProxy();
            // construct a header for constructed block
            new (node) CObjectProxy(p);
            break;
            }
    }

Listing Five

# include <stdlib.h>
# include <crtdbg.h>
void dump_client(void* p, size_t s)
    {
    _RPT1(_CRT_WARN, " Integer: %d\n", *(int*) p);  
    }
int main()
{
    _CrtSetDumpClient(dump_client);
    *(int*) _malloc_dbg(sizeof(int), _IGNORE_BLOCK, __FILE__, __LINE__) = 1;
    *(int*) _malloc_dbg(sizeof(int), _CRT_BLOCK,    __FILE__, __LINE__) = 2;
    *(int*) _malloc_dbg(sizeof(int), _NORMAL_BLOCK, __FILE__, __LINE__) = 3;
    *(int*) _malloc_dbg(sizeof(int), _CLIENT_BLOCK, __FILE__, __LINE__) = 4;
    _CrtDumpMemoryLeaks();
    return 0;
}
Output
Detected memory leaks!
Dumping objects ->
K:\test\leak.c(15) : {33} client block at 0x002D07A8, subtype 0, 4 bytes long.
 Integer: 4
K:\test\leak.c(14) : {32} normal block at 0x002D0768, 4 bytes long.
 Data: <    > 03 00 00 00 
Object dump complete.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.