Instances of dynamically created classes in C + +

Source: Internet
Author: User

Write in front: first of all, C + + is actually not dynamically creating instances of classes.

As a simple explanation, the so-called dynamic creation of an instance of a class is a class that creates and uses an "unknown" during the program's run. "Unknown" means that the program compiles without knowing which classes need to be created dynamically. For the C + + language, classes that are not known at compile time are not available at run time. So I said C + + is not possible.

But C + + can do another thing, basically to meet most of the similar needs.

I describe the creation of an instance of a class through the class name.

Go to the chase.

First describe the requirements:

Write a program implementation that creates an instance of the class through the class name (that is, a string variable) while the program is running, and that the class's declaration does not appear in the main program.

Then analyze the design:

1. The class declaration does not appear in the main program, and this class is required. It would be natural to think of a base-class pointer implementation.

2. Create a pointer to a base class for the class, you need to use the new operator.

3. Call the appropriate new operator through the class name, you need to use map plus function pointers.

4. Finally, how to construct the map before the main function executes requires a mechanism for static members to be created before the main function is run.

The code implementation is given below:

First, there is a CObject class as the base class, derived from the Cobjecta and COBJECTB two subclasses that need to be created dynamically.

Object.h

1 #ifndef __c_object_h_2 #define__c_object_h_3 4#include"ObjectFactory.h"5 6 classCObject7 {8  Public:9CObject (): ClassName ("CObject") {}Ten     Virtual~CObject () {} One     Virtual ConstSTD::stringGetClassName () A     { -         returnClassName; -     } the Private: -STD::stringClassName; - }; -  + #endif //__c_object_h_

ObjectA.h

1 #ifndef __c_object_a_h_2 #define__c_object_a_h_3 4#include"Object.h"5 6 classCobjecta: PublicCObject7 {8  Public:9Cobjecta (): ClassName ("cobjecta") {}Ten~cobjecta () {} One     ConstSTD::stringGetClassName () A     { -         returnClassName; -     } the Private: -STD::stringClassName; - }; -  + Register_class (cobjecta); -  + #endif //__c_object_a_h_

ObjectB.h

1#ifndef __c_object_b_h_2 #define__c_object_b_h_3 4#include"Object.h"5 6 classCOBJECTB: PublicCObject7 {8  Public:9COBJECTB (): ClassName ("COBJECTB") {}Ten~COBJECTB () {} One     ConstSTD::stringGetClassName () A     { -         returnClassName; -     } the Private: -STD::stringClassName; - }; -  + Register_class (COBJECTB); -  + #endif //__c_object_b_h_

Then the focus is on, the above two classes have a macro definition Register_class. is actually declaring a registered class with a static member, and dynamically creating the map by initializing the static member implementation construct.

ObjectFactory.h

1 #ifndef __c_object_factory_h_2 #define__c_object_factory_h_3 4#include <map>5#include <string>6 7typedefvoid* (*newinstancept) ();8 9 classcobjectfactoryTen { One  Public: A     Static void* CreateObject (Const Char*className) -     { -STD::MAP&LT;STD::string, newinstancept>:: const_iterator it; theit =Dyncreatemap.find (className); -         if(It = =dyncreatemap.end ()) -             returnNULL; -         Else +         { -Newinstancept NP = it->second; +             returnnp (); A         } at     } -  -     Static voidRegisterClass (Const Char*ClassName, newinstancept NP) -     { -Dyncreatemap[classname] =NP; -     } in Private: -     StaticSTD::MAP&LT;STD::string, newinstancept>Dyncreatemap; to }; +  -STD::MAP&LT;STD::string, newinstancept>cobjectfactory::d yncreatemap; the  * classRegister $ {Panax Notoginseng  Public: -Register (Const Char*ClassName, newinstancept NP) the     { + Cobjectfactory::registerclass (ClassName, NP); A     } the }; +  - #defineRegister_class (class_name) $ classclass_name# #Register $ {  -  Public:  -     Static void*newinstance () the     {  -         return Newclass_name ();Wuyi     }  the Private:  -     StaticRegister reg; Wu };  - Register class_name# #Register:: Reg (#class_name, class_name# #Register:: newinstance) About  $ #endif //__c_object_factory_h_

Finally, of course there is the main function of how to use the content.

RTTI.cpp

1#include <stdio.h>2#include"ObjectFactory.h"3#include"Object.h"4#include"ObjectA.h"5#include"ObjectB.h"6 7 intMainintargcConst Char*argv[])8 {9CObject *obja = Static_cast<cobject *> (Cobjectfactory::createobject ("cobjecta"));TenSTD::stringClassName; One     if(Obja = =NULL) A     { -printf"[ERROR] Can ' t Create Class objecta!\n"); -     } the     Else -     { -ClassName = obja->getclassname (); -printf"[OK] Create%s!\n", Classname.c_str ()); +     } -  +CObject *OBJB = Static_cast<cobject *> (Cobjectfactory::createobject ("COBJECTB")); A     if(OBJB = =NULL) at     { -printf"[ERROR] Can ' t Create Class objectb!\n"); -     } -     Else -     { -ClassName = objb->getclassname (); inprintf"[OK] Create%s!\n", Classname.c_str ()); -     } to  +     return 0; -}

This completes the so-called dynamic creation. It is important to note that in the file where the main function needs to include all the classes that need to be dynamically created, otherwise the classes and their registered classes will not be compiled at all in the process of compiling, and they will not build a dynamically created map, and the whole mechanism will fail. That's what I'm talking about. C + + is actually the reason why the class cannot be created dynamically.

It is to be said that Java is recommended if you want to create a complete dynamic. Simply look at the reflection mechanism of Java and ClassLoader will know that the original dynamic loading is so easy ...

Instances of dynamically created classes in C + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.