Question

VC++: get object reference

Asked by: HStrix

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

 

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-06-09 at 13:50:40ID21881408
Tags

error

Topic

C++ Programming Language

Participating Experts
2
Points
350
Comments
15

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. delete and void *
    I have a situation where rather than use a struct for access to elements within a database, I want to use an array of void pointers. This will allow me to create generic routines for many of the basic data access routines. When allocating space for the data, I will access a...
  2. bool vs. BOOL
    Are bool (standard C++) and BOOL (defined in Visual C++) interchangable?
  3. bool
    I have a function that I copy from book as below. But, my Borland Turbo C++ ver4.5 Windows can't compile it. It saying that undefined 'bool'. How should I fix it? bool full(){return (top == max_len -1}; Thank you.
  4. The difference between "bool" and "BOOL" in C++ ?
    in C++ Windows programming what is the difference between using the types "bool" and "BOOL" as a return type.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: jkrPosted on 2006-06-09 at 15:03:25ID: 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")

 

by: HStrixPosted on 2006-06-09 at 15:37:20ID: 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?

 

by: jkrPosted on 2006-06-09 at 15:45:17ID: 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).

 

by: HStrixPosted on 2006-06-09 at 15:52:10ID: 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()
{ ...}

...

 

by: itsmeandnobodyelsePosted on 2006-06-10 at 09:47:15ID: 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

 

by: HStrixPosted on 2006-06-10 at 13:23:10ID: 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?

 

by: itsmeandnobodyelsePosted on 2006-06-11 at 01:57:32ID: 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
 

 

by: itsmeandnobodyelsePosted on 2006-06-11 at 02:27:16ID: 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

 

by: HStrixPosted on 2006-06-11 at 02:36:29ID: 16880150

Thanks,
so I'll close this question.
It is not solved, but..

 

by: itsmeandnobodyelsePosted on 2006-06-11 at 02:48:16ID: 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

 

by: HStrixPosted on 2006-06-11 at 03:42:28ID: 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();
}

-----

 

by: itsmeandnobodyelsePosted on 2006-06-11 at 04:17:51ID: 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.




 

by: HStrixPosted on 2006-06-11 at 05:00:37ID: 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?

 

by: HStrixPosted on 2006-06-11 at 06:04:44ID: 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 :-(

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...