If I have the class name in a string varibale, how can I instantiate an object of that class?

I am just thinking of COM and CORBA implementations where C++ object is instantiated from the data in the stream. How can I implement it?

You mean something like?

#include <iostream>
#include <string>

class Foo
{
public:
       std::string sayHello()
       {
         return "Hello";
       }
};

int main()
{
    Foo test;
    std::cout << test.sayHello();
    
    std::cin.get();
}

I think he might mean a situation where you could take in a class name from the user and instantiate a class, so in your example above:

string classname;
std::cin >> classname;
(it's invalid but...)  classname * cn = new classname();

I think for a finite number of cases you could use a bunch of if/else if statements:

if(classname == "Foo")
     Foo * foo = new Foo();
elseif(classname  == "Bar")
     Bar * bar = new Bar();
...

>>If I have the class name in a string varibale, how can I instantiate an object of that class?

Your question is not very clear, but my guess would be that you meant
something like :

class Foo
{
   public Foo() { }
};

int main()
{
    string className = "Foo";
    Foo * foo; //not instantiated but waiting in a sense to be created.

    if( className == "Foo")  //a string variable has the class name FO
       foo = new Foo(); //so create a new class of that object

   //after foo is done being used with
  delete foo;
}

Edited 7 Years Ago by firstPerson: n/a

This article has been dead for over six months. Start a new discussion instead.