peace
peace

Reputation:

How can I inherit an MFC dialog box?

I have created a dialog box (cMyDialog). I am planning to duplicate cMyDialog and call it cMyDialog2. How can I do inheritance in MFC? I want cMyDialog2 to inherit all the IDDs from cMyDialog1 so that I do not have to copy and paste the code from cMyDialog1 to cMyDialog2. The purpose of cMyDialog2 is to inherit all the functions from cMyDialog1 and to add some extra functions in it.


Thank you very much for your reply. I am not quite sure about the IMPLEMENT_DYNAMIC. Below is a short snippet of my code. Can you please review it and help me if I misunderstood the macro?

// cMyDialog1.cpp : implementation file

cMyDialog1::cMyDialog1(void * pMsgData, CWnd* pParent /*=NULL*/): CDialog(cMyDialog1::IDD, pParent)

{ //codes....
}

BOOL cMyDialog1::OnInitDialog() 

{
    CDialog::OnInitDialog();
...
}


//cMyDialog2.cpp

cMyDialog2::cMyDialog2(void * pMsgData, CWnd* pParent /*=NULL*/)
    : CMyDialog1(cMyDialog2::IDD, pParent)

{ //codes....
   IMPLEMENT_DYNAMIC(cMyDialog2, cMyDialog1)
}

I am able to inherit from CMyDialog via the DECLARE_DYNAMIC and IMPLEMENT_DYNAMIC method. Thanks a lot for your help, Adam.

But I was unable to get the second part of my question to work. I wanted to add some extra functions in the child dialog box, CMyDialog1, such as adding a "Save As" button, but I was unable to do it. Is it because CMyDialog1 is an inherited dialog from CMyDialog and hence, I can't add in new functions? How can I add new functions in the inherited dialog box?

Upvotes: 4

Views: 3676

Answers (2)

zar
zar

Reputation: 12247

This maybe considered as addendum to Adam Piece answer. It is also important to understand the role of DoDataExchange() when deriving from another dialog. Either the derived class (cMyDialog2) shall not implement this function or if it is implemented (recommended) it should call base version of it like below:

void cMyDialog2::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    cMyDialog::DoDataExchange(pDX);
}

If this is not done correctly, the controls on the dialog will not be created and the dialog may crash as a result when invoked/executed.

Upvotes: 1

Adam Pierce
Adam Pierce

Reputation: 34375

Yes you can inherit from a CDialog-derived class. You just need to add a few macros like DECLARE_DYNAMIC and a few others to satisfy MFC. Here is an example. You can use this as a starting point:

In the .h file:

class cMyDialog2
  : public cMyDialog
{
  DECLARE_DYNAMIC(cMyDialog2)

pulic:
  cMyDialog2();
  virtual ~cMyDialog2();

protected:
  DECLARE_MESSAGE_MAP()
};

In the .cpp file:

#include "cMyDialog2.h"

IMPLEMENT_DYNAMIC(cMyDialog2, cMyDialog)

BEGIN_MESSAGE_MAP(cMyDialog2, cMyDialog)
END_MESSAGE_MAP()

cMyDialog2::cMyDialog2()
{
}

...etc.

Upvotes: 7

Related Questions