class *a = new ?;

F

feribiro

Hi,

could you tell me please how it is possible to pass the type of a
class to a function as a parameter, and then initiate a new class of
that type?

class A {...}
class B : public A {...}
class C : public A {...}

void Main()
{
Create(B);
Create(C);
}

void Create(??? param)
{
A *a = new ??param??;
delete a;
}

Thank you very much
 
S

SG

Hi,

could you tell me please how it is possible to pass the type of a
class to a function as a parameter, and then initiate a new class of
that type?

class A {...}
class B : public A {...}
class C : public A {...}

void Main()
{
 Create(B);
 Create(C);
}

void Create(??? param)
{
 A *a = new ??param??;
 delete a;
}

Thank you very much

You cannot do this dynamically like in other languages which keep
enough meta data about classes in memory for "reflection" (I'm
thinking of Java in this case) -- at least not without getting your
hands dirty (building registries, registering types, etc by yourself).

But you can do it easily at compile-time. In your case ("Create(B);")
you already know the type at compile-time (B)...

class A
{
public:
virtual ~A() {}
//...
};

class B : public class A {...};
class C : public class A {...};

template<typename T>
void Create()
{
A* a = new T;
delete a;
}

int main()
{
Create<B>();
Create<C>();
}

Note: The class A must have a virtual destructor because you invoke
delete with a pointer of type A* that points to a possibly derived
object. Inheritance must be public in your case. The main function's
name is all lower case and its return type is int.

Cheers,
SG
 
P

Pascal J. Bourguignon

SG said:
You cannot do this dynamically like in other languages which keep
enough meta data about classes in memory for "reflection" (I'm
thinking of Java in this case) -- at least not without getting your
hands dirty (building registries, registering types, etc by yourself).

Well this can be done easily enough with boost::lambda.
Or somewhat less easily by defining factory functions.

typedef A* (*factory)();
A* makeInstance_B(){ return new B(); }
A* makeInstance_C(){ return new C(); }

void Create(factory f){
A* a=f();
a->doSomething();
delete a;
}

Create(&makeInstance_B);
Create(&makeInstance_C);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top