Topic : MFC Introduction
Author : Prof Devi
Page : << Previous 4  
Go to page :


of the base class that the current class is derived from.

The Box #1, Box # 2, and Box #3 are examples of using the macros DECLARE_DYNCREATE and IMPLEMENT_DYNCREATE.   The class Counter is given the extra functionality's of MFC Run time type identification and dynamic object creation through the class CRuntimeClass.  

// Box #1: DECLARE)DYNCREATE
//    File Name:  Counter.h

#ifndef Counter_h
#define Counter_h

#include <afxwin.h>

class Counter:public CObject
   {
   int mCounter;
   public:
   Counter();
   ~Counter();
   void Inc(void);
   int GetCount(void) const;

   DECLARE_DYNCREATE(Counter);
   };


#endif Counter_h



// Box #2 : IMPLEMENT DYNCREATE
//   File Name: Counter.cpp

#include <afxwin.h>
#include "Counter.h"

/////////////////////////////
IMPLEMENT_DYNCREATE(Counter,CObject);

/////////////////////////////
Counter::Counter()
   { mCounter=0; }

/////////////////////////////
Counter::~Counter()
   { }

/////////////////////////////
void Counter::Inc(void)
   {  ++mCounter; }

/////////////////////////////
int Counter::GetCount(void) const
   { return mCounter; }



// Box #3: Dynamic Object Creation
// File Name: main.cpp

#include <afxwin.h>
#include <stdio.h>
#include "Counter.h"


//////////////////////////////////////
int main(void)
   {
   if(AfxWinInit(::GetModuleHandle(NULL),NULL,::GetCommandLine(),0)==FALSE)
      {  perror("Unable to init MFC\n");  return 1; }


   CRuntimeClass *ret=RUNTIME_CLASS(Counter);

   CObject *newobj=ret->CreateObject();

   if(newobj==NULL) { printf("Unable to create object...\n"); return 1; }


   // Check if new object is an instance of COunter
   printf("Class Name of new object: %s\n",newobj->GetRuntimeClass()->m_lpszClassName);

   
   if(newobj->GetRuntimeClass()->IsDerivedFrom(RUNTIME_CLASS(Counter))==FALSE)
      {
      printf("Severe Error: Object Creation created the wrong type");
      return 2;
      }

   printf("Everything is Ok!!!!\n");

   Counter *count=(Counter *)newobj;

   for(int i=1;i<=100;++i)
      {  count->Inc();  }

   printf("Final Count: %d\n",count->GetCount());

   delete count;  return 0;
   }


CFile


The CFile class is used for reading and writing to files.

Page : << Previous 4