Create object instance of different types

F

f.f

class A
{
....
};

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

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

T* createObject()
{
T* ptr = new T();
return ptr;
}

I wanna use createObject() to create object instance of either class B
or class C?
What approach should I use? Should I use template?

f.f
 
A

Andre Kostur

class A
{
...
};

class B : public A
{
...
};

class C : public A
{
...
};

T* createObject()
{
T* ptr = new T();
return ptr;
}

I wanna use createObject() to create object instance of either class B
or class C?
What approach should I use? Should I use template?

How does createObject know which of A, B, or C to create? Offhand I
don't see how a template makes it easier:

template<class T>
T * createObject()
{
return new T();
}

All this seems to do is obfuscate the code by hiding the use of "new",
since you'd have to specify the type to be created at the call site
anyway. Why not just use "new" whererever you're using "createObject"?
 
R

red floyd

f.f said:
class A
{
...
};

class B : public A
{
...
};

class C : public A
{
...
};

T* createObject()
{
T* ptr = new T();
return ptr;
}

I wanna use createObject() to create object instance of either class B
or class C?
What approach should I use? Should I use template?

You might want to google for "Factory Pattern"
 

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

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,739
Latest member
Clint8040

Latest Threads

Top