Dynamic Creation

You've already learned that the DECLARE and IMPLEMENT macros add a static CRuntimeClass object to a class. If you use the DECLARE_DYNCREATE or DECLARE_SERIAL macro (and the corresponding IMPLEMENT macro), you get an additional static member function CreateObject (distinct from CRuntimeClass::CreateObject) in your class. Here's an example:

CObject* CMyClass::CreateObject() {     return new CMyClass; }

Obviously, CMyClass needs a default constructor. This constructor is declared protected in wizard-generated classes that support dynamic creation.

Now look at the code for the CRuntimeClass::CreateObject function:

CObject* CRuntimeClass::CreateObject() {     return (*m_pfnCreateObject)(); }

This function makes an indirect call to the CreateObject function in the target class. Here's how you would dynamically construct an object of class CMyClass:

CRuntimeClass* pRTC = RUNTIME_CLASS(CMyObject); CMyClass* pMyObject = (CMyClass*)pRTC->CreateObject();

Now you know how document templates work. A document template object has three CRuntimeClass* data members initialized at construction to point to the static CRuntimeClass data members for the document, frame, and view classes. When CWinApp::OnFileNew is called, the framework calls the CreateObject functions for the three stored pointers.



Programming Microsoft Visual C++
Programming Microsoft Visual C++
ISBN: 1572318570
EAN: 2147483647
Year: 1997
Pages: 332

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net