Solved

VC++: get object reference

Posted on 2006-06-09
15
673 Views
Last Modified: 2012-05-05
Hello Experts,
I created an MFC application  MyUtil (in .Net 2003 unmanaged C++) as SDI and added a resource form (IDD_FORMVIEW).
Now I added an new class CNew with CView as base class.
This compiles OK.
I need to create an instance of this new class inside MyUtil.cpp.
I couldn't findout how to do that.
Some code in the new class looks as follows:
---
// New.cpp : Implementation file
//
#include "stdafx.h"
#include "MyUtil.h"
#include "New.h"
// CNew

//IMPLEMENT_DYNCREATE(CNew, CView)

bool IsNew()
{ ...}

CNew::CNew()
{
}

CNew::~CNew()
{
}

BEGIN_MESSAGE_MAP(CNew, CView)
END_MESSAGE_MAP()

void CNew::OnDraw(CDC* pDC)
{
  CDocument* pDoc = GetDocument();
  // TODO:
}

// CNew-Diagnose

#ifdef _DEBUG
void CNew::AssertValid() const
{
      CView::AssertValid();
}
void CNew::Dump(CDumpContext& dc) const
{
      CView::Dump(dc);
}

bool CNew::detectNew()
{
      bool boolNew = IsNew();
      return boolNew;
 }
#endif //_DEBUG
// CNew-Messagehandler
---
//New.h : Header file

#pragma once

// CNew-View
class CNew : public CView
{
DECLARE_DYNCREATE(CNew)

protected:
      CNew();          
      virtual ~CNew();

public:
      virtual void OnDraw(CDC* pDC);      
#ifdef _DEBUG
      virtual void AssertValid() const;
      virtual void Dump(CDumpContext& dc) const;
#endif

protected:
  DECLARE_MESSAGE_MAP()

bool CNew::detectNew();
};
---
I tried the following (it is not working):
---
  CNew myNew1;
  bool boolNew = myNew1.detetcNew();
---
The intellisense offered me
  CNew::detectNew();
But compilation ends in error.

If anyone knows what I need to do,
please supply an appropriate information.

Thank you for any help.

  HStrix

 
0
Comment
Question by:HStrix
  • 7
  • 5
  • 2
15 Comments
 
LVL 86

Assisted Solution

by:jkr
jkr earned 150 total points
ID: 16874272
Since you're using DECLARE_DYNCREATE(CNew),

try

CRuntimeClass* pRuntimeClass = RUNTIME_CLASS( CNew );
CNew* pNew = (CNew*)pRuntimeClass->CreateObject();

  bool boolNew = pNew->detetcNew();

See also http://msdn.microsoft.com/library/en-us/vccore98/HTML/_core_cobject_class.3a_.dynamic_object_creation.asp ("Dynamic Object Creation")
0
 

Author Comment

by:HStrix
ID: 16874431
Thanks, I get
CRuntimeClass* pRuntimeClass = RUNTIME_CLASS( CNew ); // error C2065: 'classCNew': undeclared identifier
                                                                                         // error C2653: 'CNew': No class or namespace
CNew* pNew = (CNew*)pRuntimeClass->CreateObject(); // error C2065: 'classCNew': undeclared identifier

Any idea?
0
 
LVL 86

Expert Comment

by:jkr
ID: 16874461
Well, if you have

DECLARE_DYNCREATE(CNew)

you should also have a

IMPLEMENT_DYNCREATE(CNew,CView)

in the .cpp file (outside of any functions).
0
 

Author Comment

by:HStrix
ID: 16874494
Yes, it's there; the file starts with ...
---
// New.cpp : Implementation file
//
#include "stdafx.h"
#include "MyUtil.h"
#include "New.h"
// CNew

IMPLEMENT_DYNCREATE(CNew, CView) // <== there was a copy error in my question, it was commented

bool IsNew()
{ ...}

...
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16877595
In an SDI you should use your document class to add a new view to the existing document-

Add a  member of type CSingleDocTemplate to your document class, e. g. m_pNewTemplate, and init it to NULL in the initialiser list of CMyDoc::CMyDoc

Add two member functions like these below to your document class:

CSingleDocTemplate* CMyDoc::CreateNewTemplate()
{
  return new CSingleDocTemplate( IDR_MAINFRAME,
                                                  RUNTIME_CLASS(CMyDoc),
                                                  RUNTIME_CLASS(CMainFrame),
                                                  RUNTIME_CLASS(CNew));
}

void CMyDoc::CreateNewView()
{  
      CFrameWnd* pFrame      = m_pNewTemplate->CreateNewFrame(this, NULL);
      m_pNewTemplate->InitialUpdateFrame(pFrame, this, TRUE);
}


Add a new menu entry to the main menu (here IDR_MAINFRAME) which is supposed to invoke the view. Add a handler for the new menu item by using class wizard to your document class. The handler function should look like taht:

void CMyDoc::OnNewView()
{
   if (m_pNewTemplate == NULL)
   {
        m_pNewTemplate = CreateNewTemplate();
        theApp.AddDocTemplate(m_pNewTemplate);
   }
   else
   {
      CDocument*       pDoc = this;
      POSITION pos = pDoc->GetFirstViewPosition();
      CView* pView = pDoc->GetNextView(pos);
      while ( pView != NULL  &&  !pView->IsKindOf(RUNTIME_CLASS(CNew)) )
               pView = pDoc->GetNextView(pos);
      if (pView != NULL)
        {
           pView->GetParentFrame()->ActivateFrame();
           return;
        }
    }
    CreateNewView();
}


That should do  the job (beside of typos).

Regards, Alex
0
 

Author Comment

by:HStrix
ID: 16878329
Thanks,
but I couldn't make this working.
The file MyUtilDoc.h looks now as follows
---
// MyUtilDoc.h : Interface of class CMyUtilDoc
//
#pragma once
class CMyUtilDoc : public CDocument
{
protected: //
      CMyUtilDoc();
      DECLARE_DYNCREATE(CMyUtilDoc)
// Attributes
public:
// Operations
public:
//
      public:
      virtual BOOL OnNewDocument();
      virtual void Serialize(CArchive& ar);
// Implementation
public:
      virtual ~CMyUtilDoc();
#ifdef _DEBUG
      virtual void AssertValid() const;
      virtual void Dump(CDumpContext& dc) const;
#endif
protected:
//Generated functions
protected:
      DECLARE_MESSAGE_MAP()
      // Generated OLE-Dispatch
      DECLARE_DISPATCH_MAP()
      DECLARE_INTERFACE_MAP()
public:
      CSingleDocTemplate m_pNewTemplate(void);
};
---
Anf MyUtilDoc.cpp is:
---
// MyUtilDoc.cpp : Implementiation of class CMyUtilDoc
//

#include "stdafx.h"
#include "MyUtil.h"

#include "MyUtilDoc.h"
#include ".\myutildoc.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CMyUtilDoc

IMPLEMENT_DYNCREATE(CMyUtilDoc, CDocument)

BEGIN_MESSAGE_MAP(CMyUtilDoc, CDocument)
      ON_COMMAND(ID_FILE_SEND_MAIL, OnFileSendMail)
      ON_UPDATE_COMMAND_UI(ID_FILE_SEND_MAIL, OnUpdateFileSendMail)
END_MESSAGE_MAP()

BEGIN_DISPATCH_MAP(CMyUtilDoc, CDocument)
END_DISPATCH_MAP()

//  Disp Interface in .IDL file

// {38302831-9967-4123-B2B3-2A27A84E6009}
static const IID IID_IMyUtil =
{ 0x38302831, 0x9967, 0x4123, { 0xB2, 0xB3, 0x2A, 0x27, 0xA8, 0x4E, 0x60, 0x9 } };

BEGIN_INTERFACE_MAP(CMyUtilDoc, CDocument)
      INTERFACE_PART(CMyUtilDoc, IID_IMyUtil, Dispatch)
END_INTERFACE_MAP()

// CMyUtilDoc Create/Destroy

CMyUtilDoc::CMyUtilDoc()
{
      // TODO: Code für One-Time
      EnableAutomation();
      AfxOleLockApp();
}

CMyUtilDoc::~CMyUtilDoc()
{
      AfxOleUnlockApp();
}

BOOL CMyUtilDoc::OnNewDocument()
{
      if (!CDocument::OnNewDocument())
            return FALSE;
      // TODO:
      // (SDI)
      return TRUE;
}

// CMyUtilDoc Serialisation

void CMyUtilDoc::Serialize(CArchive& ar)
{
      if (ar.IsStoring())
      {
            // TODO:
      }
      else
      {
            // TODO:
      }
}

// CMyUtilDoc Diagnose

#ifdef _DEBUG
void CMyUtilDoc::AssertValid() const
{
      CDocument::AssertValid();
}

void CMyUtilDoc::Dump(CDumpContext& dc) const
{
      CDocument::Dump(dc);
}
#endif //_DEBUG

CSingleDocTemplate CMyUtilDoc::m_pNewTemplate(void)
{
      return CSingleDocTemplate();
}

CSingleDocTemplate* CMyUtilDoc::CreateNewTemplate()     // <= error C2039 not an element

{
  return new CSingleDocTemplate( IDR_MAINFRAME,
                                                  RUNTIME_CLASS(CMyUtilDoc),
                                                  RUNTIME_CLASS(CMainFrame),  // error C2065 undefined
                                                  RUNTIME_CLASS(CNew));          // error C2065 undefined
}

void CMyUtilDoc::CreateNewView()   // <= error C2039
{  
     CFrameWnd* pFrame     = m_pNewTemplate->CreateNewFrame(this, NULL); // error C2065 m_pNewTemplate undeclared
     m_pNewTemplate->InitialUpdateFrame(pFrame, this, TRUE);
}
---
Any ideas?
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16880094
>>>> CSingleDocTemplate m_pNewTemplate(void);

That is a member function. My sample needs member data (remove the '(void)'). That member has the purpose to save the pointer to CSingleDocTemplate cause it was needed only once.

>>>> CSingleDocTemplate* CMyUtilDoc::CreateNewTemplate()     // <= error C2039 not an element
>>>> void CMyUtilDoc::CreateNewView()   // <= error C2039

You need to define these member functions as public in CMyUtilDoc class:


class CMyUtilDoc : public CDocument
{
      ....
public:
      CSingleDocTemplate* CMyUtilDoc::CreateNewTemplate();
      void CMyUtilDoc::CreateNewView();

private:
      CSingleDocTemplate m_pNewTemplate;  // that member doesn't need to be public
};

Regards, Alex
 
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16880141
Note, the MFC SDI or MDI framework with application, templates, frames, documents and views isn't easy to understand even for non-beginners. I would recommend you to study some of the sample projects that came with the VC6 cd before trying it at your own.

Generally, in an SDI project there is one application object, one frame and  one document object. In your case the (generated) classes CMyUtilApp, CMainFrame and CMyMultiDoc were used by the framework for these objects. The first two class objects (CMyUtilApp, CMainFrame) already were creted prior to the call of CMyUtilApp::InitInstance. In that member function (generated as well) a CSingleDocTemplate was used to generate a document and associated view object and connect  both new objects to the frame class. Alll these classes were passed to the template (what is simply a helper) by RUNTIME_CLASS pointers what  is a helper (macro) too. Using those helpers, MFC framework can create new class objects of the classes passed by name. The whole thing is called a factory.

If you want to add an additional view (additional to the initial view already visible, so you have to view windows after that if you don't hide the initial view) you need to repeat the things initially done in CMyUtil::InitInstance. You have to create a new template where document, frame and view classes were associated and you have to call your (existing) document  to actually create the new view. All that was done by the sample code I posted above.

Regards, Alex
0
 

Author Comment

by:HStrix
ID: 16880150
Thanks,
so I'll close this question.
It is not solved, but..
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16880166
>>>> It is not solved, but..

What is the problem? You shouldn't close questions if they are not solved. I am pretty sure that we could get the sample to work - means you would see your second view - though we couldn't solve all additional questions that might arise later...

Regards, Alex
0
 

Author Comment

by:HStrix
ID: 16880277
Sorry, I didn't read your last but one comment, I overlooked it.
My impression was, that I should first learn more..
-----------
Now I inserted your code and get...
-----
CSingleDocTemplate* CMyUtilDoc::CreateNewTemplate()     // <= this error C2039 is gone

{
  return new CSingleDocTemplate( IDR_MAINFRAME,
                                                  RUNTIME_CLASS(CMyUtilDoc),
                                                  RUNTIME_CLASS(CMainFrame),  // error C2065 undefined: still there; new C2653
                                                  RUNTIME_CLASS(CNew));          // error C2065 undefined: still there; new C2653
}

void CMyUtilDoc::CreateNewView()   // <= this error C2039 is gone
{  
     CFrameWnd* pFrame     = m_pNewTemplate->CreateNewFrame(this, NULL); // error C2065 m_pNewTemplate undeclared is gone; new are errors C2227and C2819 here
     m_pNewTemplate->InitialUpdateFrame(pFrame, this, TRUE);   // errors C2227 and C2819 new here
}

CMyUtilDoc::CMyUtilDoc()
{                          //  error C2512 new here
      // TODO:

      EnableAutomation();

      AfxOleLockApp();
}

-----
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 200 total points
ID: 16880370
>>>> RUNTIME_CLASS(CMainFrame),  // error C2065 undefined: still there; new C2653

Did you include mainfrm.h ?

Normally in a MFC SDI project the main frame class is generated as CMainFrame. But maybe you changed the name. Check all generated class header files for a class derived from CFrameWnd (or CMDIFrameWnd) and use that class instead of CMainFrame.

'CNew' must be replaced with the name of your new view class and you have to include the header of that new class.

>>>> new are errors C2227and C2819 here

It was a typo from me:

>>>> CSingleDocTemplate m_pNewTemplate;  // that member doesn't need to be public

It must be a pointer so replace it by

      CSingleDocTemplate* m_pNewTemplate;  // that member doesn't need to be public

Regards, Alex

BTW, I'll leave now and will return tomorrow.




0
 

Author Comment

by:HStrix
ID: 16880495
You were right,
I needed to insert mainfrm.h;
I also needed to insert New.h.
After this I inserted into myutil.cpp as suggested by jkr:
---
CRuntimeClass* pRuntimeClass = RUNTIME_CLASS( CNew);
CNew* pNew = (CNew*)pRuntimeClass->CreateObject();
bool boolNew = pNew->detectNew();
---
So, my remaining "problem" is to distribute proper points :-)
What could I do?
0
 

Author Comment

by:HStrix
ID: 16880833
Using the support of the moderator I was able to manage the split.

Btw., I asked a while ago another question at
    http://www.experts-exchange.com/Programming/Programming_Languages/Cplusplus/Q_21856744.html
Perhaps you could have a look at this?
Till now nobody could answer this question :-(
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now