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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top