You are here:

C++/Dynamic object creation

Advertisement


Question
Hi,
Can you tell me a way how to create an object if the class is passed as a string dynamically?
The class name is stored in a file and after reading it from the file, the respective object needs to be created.


Answer
The short answer is that you cannot do this directly in C++.

C++ is a statically typed and compiled language. All types must therefore be known at the time of compilation and _all_ object creation must be known to use a specific type at compilation time also.

So, although we can create objects dynamically at runtime using new (and destroy them using delete), the compiler must always know the type of the object that will be created.

That is all such requests to create an object from say a string name at runtime _must_ come down to a statement something like:

   new ClassName;

that has already been written and compiled / linked into the code.

However, if you have only a fixed number of classes for which you require objects to be created at runtime then of course we can write code to manually examine a string and route object creation to the relevant new statement. Of course this effectively requires that we have some common base type all such run-time specified created objects share and use polymorphism (virtual member functions in C++) to implement the requires differing behaviours.

The most obvious and basic example of such code would be to use an if-else if block to check the read string for a match to each class name and perform the required new.

For example suppose we have the following class hierarchy (I have used struct rather than class for brevity) that support a simple Greet operation:

   struct BaseClassType
   {
     virtual ~BaseClassType() {}
     virtual void Greet() = 0;
   };
   
   struct ClassName1 : BaseClassType
   {
     virtual void Greet();
   };

   struct ClassName2 : BaseClassType
   {
     virtual void Greet();
   };

   struct ClassName3 : BaseClassType
   {
     virtual void Greet();
   };

   // in implementation file
   
   // include header for BaseClassType etc. definitions
  
   #include <iostream>

   void ClassName1::Greet()
   {
       std::cout << "Hello, I am a ClassName1 object\n";
   }
   
   void ClassName2::Greet()
   {
       std::cout << "Hello, I am a ClassName2 object\n";
   }
   
   void ClassName3::Greet()
   {
       std::cout << "Hello, I am a ClassName3 object\n";
   }

Then we could write a function to create instances of ClassName1, ClassName2 and ClassName3 from the strings "ClassName1", "ClassName2" and "ClassName3":

   BaseClassType * ObjectFactory( std::string className )
   {      
       if ( "ClassName1" == className )
       {
         return new ClassName1;
       }
       else if  ( "ClassName2" == className )
       {
         return new ClassName2;
       }
       else if  ( "ClassName3" == className )
       {
         return new ClassName3;
       }
   // etc...
       else // does not match a known class name...
       {
         return 0; // ...return a null pointer value.
       }
   }

Of course this sort of thing gets to be a maintenance nightmare so we often find glue code around such things - in older frameworks I used this used to involve quite a bit of nasty macro hackery. Another point against such a solution is that as the number of supported classes increases the efficiency decreases especially for creating objects of classes further down the if .. else if ... chain. However I have seen and used code that worked like the above (albeit via macro expansions), until just this performance penalty became too much. When that happened those maintaining the code re-worked it to use string-factory mappings or similar. Here is one possible approach using C++ standard library containers:

   struct BaseFactory      // Each class which can have run time specified object creation
   {          // has an equivalent factory class that provides a Create virtual
         // function override
       virtual ~BaseFactory() {}

       virtual BaseClassType * Create() = 0;
   };
   
   struct ClassName1Factory : BaseFactory
   {
       BaseClassType * Create();
   };
   
   struct ClassName2Factory : BaseFactory
   {
       BaseClassType * Create();
   };
   
   struct ClassName3Factory : BaseFactory
   {
       BaseClassType * Create();
   };
   
   // etc..
  
   // in implementation file

   BaseClassType * ClassName1Factory::Create()
   {
       return new ClassName1;
   }

   BaseClassType * ClassName2Factory::Create()
   {
       return new ClassName2;
   }

   BaseClassType * ClassName3Factory::Create()
   {
       return new ClassName3;
   }

   // etc..

The above code fragments show a base factory class type (in fact I used struct again for brevity) that defines a pure virtual function to create and return a pointer to an object derived from BaseClassType. I show one example concrete factory class implementation for creating ClassName1 objects. Other factory types follow this basic scheme. As you can see this is where the new statements get put in this scheme!

We can make the creation of the factory classes generic by writing a single Factory class template like so:

   template <class C>
   struct Factory  : BaseFactory
   {
       BaseClassType * Create();
   };
   
   template <class C>
   BaseClassType * Factory<C>::Create()
   {
       return new C;
   }

In which case we could create factory objects for our ClassName1, ClassName2 and ClassName3 classes as below:

     Factory<ClassName1>  cn1Factory;
     Factory<ClassName2>  cn2Factory;
     Factory<ClassName3>  cn3Factory;

Next we create a mapping between the name strings and pointers to BaseFactory objects and insert one name, factory pointer pair entry per supported class name. In fact as you can see the factory object pointers will be pointers to objects of the concrete derived factory types.

   #include <map>          // for standard C++ library std::map class template
   #include <string>       // for std::string
   #include <utility>      // for std: :pair etc.

   typedef std::map<std::string, BaseFactory*>     ClassNameFactoryMap;
   
   // ...
   
   ClassNameFactoryMap    factoryMap;
   
   // ...

   factoryMap.insert( std::make_pair(std::string("ClassName1"), new Factory<ClassName1>) );
   factoryMap.insert( std::make_pair(std::string("ClassName2"), new Factory<ClassName2>) );
   factoryMap.insert( std::make_pair(std::string("ClassName3"), new Factory<ClassName3>) );
   
   // ...
   
Now we can look up the factory by name in the map and call the Create function on the returned factory or raise an error if no factory is found for the supplied name:
  
   BaseClassType * ObjectFactory2( std::string className )
   {
       ClassNameFactoryMap::iterator factoryPos( factoryMap.find(className) );

       if ( factoryPos != factoryMap.end() )
       {
         BaseFactory * pFactory( factoryPos->second );
         return pFactory->Create();
       }
       else  // no factory found...
       {
         throw std::runtime_error("Attempt to dynamically request instance of unsupported class type");
       }
   }

Some of the complexity above is due to the day to day usage of C++ library map types.

I have only shown fragments of a whole solution to give you an idea of what sort of things need to be done. Full implementations may be able to make use of templates and/or macros to tidy things up - or at least sweep them under the carpet as it were <g>. Especially not the factoryMap object needs to be accessible to both the map filling function and ObjectFactory2 and any other functions that use it - in a real implementation it would be better to wrap all of this up in a class.

Now C++ has support for type information in the form of the typeid operator and the library std::type_info class (include the <typeinfo> header). It does not give us very much information on types, and then only for types with virtual functions _if_ RTTI (runtime type information) is enabled (RTTI can be disabled as an option for many compilers).

Of particular interest here is the std::type_info::name member function - which returns a name as a zero terminated array of char (i.e. a C-style string). What this string contains is as the C++ standard says "implementation defined" - so it could be the name of the class, as char characters as we would expect, the name of the class as a multibyte string suitable for conversion to a std::wstring (a wide string), an empty string, or something else. For example Microsoft Visual C++ 2005's implementation of std::type_info::name returns strings of the form "struct ClassName1" rather than just "ClassName1".

However if for your compiler(s) std::type_info::name() returns a reasonable name then it can be used to generate the names of the classes supported by the factory map, for example using the string returned by td::type_info::name as is we could rewrite the factoryMap insertion code like so:

   factoryMap.insert( std::make_pair(std::string(typeid(ClassName1).name()), new Factory<ClassName1>) );
   factoryMap.insert( std::make_pair(std::string(typeid(ClassName2).name()), new Factory<ClassName2>) );
   factoryMap.insert( std::make_pair(std::string(typeid(ClassName3).name()), new Factory<ClassName3>) );

The form these inserts are now in is much more amenable to being made generic using template techniques as each insertion is only dependent on the class C++ identifier name and not other classes (such as ClassName1Factory etc.) or literal string data like "ClassName1":

   template <class C>
   void RegisterClass()
   {
       factoryMap.insert( std::make_pair(std::string(typeid(C).name()), new Factory<C>) );
   }

We then replace the factoryMap.insert calls with calls to RegisterClass like so:

     RegisterClass<ClassName1>();
     RegisterClass<ClassName2>();
     RegisterClass<ClassName3>();

Again, although for the example code shown here I am using global data and non-member functions a real implementation would almost certainly wrap up many of these details in one or more classes and / or class templates.

Hope this has given you some idea as to how to go about achieving what you are after with C++. I have only shown a couple of obvious approaches - there are many more arrangements that we could use to solve this problem. What is good for you depends on your situation.

If you are interested in this subject then you might like to look at some of the various framework libraries that are around such as the Microsoft MFC and see if they support such idioms and if so how they go about doing it. Another area to look at is at are the factory types. There is an interesting chapter on object factories in Andrei Alexandrescu's eye opening book "Modern C++ Design Generic Programming and Design Patterns Applied".  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.