0

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?

4
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by firstPerson
0

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();
}
0

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();
...
0

>>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 by firstPerson: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.