svKris
svKris

Reputation: 783

create instance

i have a string which contains the class name. i want to create an instance for that class..

i.e

class  Test
{}

in main function

String str="Test";

i have to create instance of the Test class using str variable only...

Upvotes: 1

Views: 465

Answers (8)

CashCow
CashCow

Reputation: 31435

The generic OOP technique you are trying to describe is called the Abstract Factory pattern, whereby you read data and then decide at runtime what type of class to create.

Normally the class will derive from a known base or else it will have to be some kind of variant type.

For a class that derives from a known base you would then go on to call its virtual/abstract methods (polymorphism). With a variant type you would probably "visit" it.

Upvotes: 0

Sulla
Sulla

Reputation: 8019

In Java you have support for reflections by default. In native C++ you don't have reflections. If you need reflections in C++, try using frameworks like Qt.

Upvotes: 1

aioobe
aioobe

Reputation: 420951

You have to use a technique called reflection. Here is the Wikipedia article on Reflection (computer programming).

For Java: Have a look at the Class class, specifically the Class.newInstance method.

Here is a simple "Hello World" program to demonstrate:

public class Test {

    public static void main(String[] args) throws Exception {
        String className = "Test";

        Class c = Class.forName(className);
        Object o = c.newInstance();

        ((Test) o).method();
    }

    public void method() {
        System.out.println("Hello World");
    }
}

Upvotes: 3

vz0
vz0

Reputation: 32923

With Java you need to use the Reflection API:

String className = "Test";
Test newInst = (Test)Class.forName(className).newInstance();

C++ has no native Reflection equivalent to Java, so you need to implement it yourself:

void* newInstance(std::string className) {
    if (className == "Test") {
        return new Test();
    }

    return 0;
}

Upvotes: 2

Ramesh
Ramesh

Reputation: 3881

Class.forName(str).newInstance();

The above code returns an object of the class. Make sure 'str' has fully qualified class name.

Upvotes: 1

peoro
peoro

Reputation: 26060

You cannot do it natively in C++. Will need to simulate reflection by using some structures (a lookup table maybe) that will associate strings to types, which will create objects for you.

Upvotes: 1

user467871
user467871

Reputation:

Test t = (Test) Class.forName(className).newInstance()

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

try

Object obj = Class.forName(str).newInstance();

Upvotes: 0

Related Questions