RE: [Dev-C++] Help with creating objects dynamically
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Marc H. <ma...@e-...> - 2003-07-22 08:12:42
|
Hi Somanathan,
There's probably a million different ways of doing this. I would =
probably
start by creating a NewPerson method defined something like (and =
defines):
#define PERSON_WORKER 1
#define PERSON_CLERK 2
#define PERSON_MANAGER 3
base* NewPerson(int nType)
{
switch(nType)
{
case PERSON_WORKER:
return (base*) new worker;
case PERSON_CLERK:
return (base*) new clerk;
case PERSON_MANAGER:
return (base*) new manager;
default:
return (base*) NULL;
}
}
And then your function becomes:
some_func(int i)
{
base *b =3D NewPerson(i);
b->any_common_func();
}
Then you only have to maintain the switch in NewPerson().
__________________________________
Marc Heiligers
-----Original Message-----
From: Somanathan Kaimal [mailto:som...@wi...]=20
Hi Gurus,
I would like to take this discussion to another turn,
Say if I have requirement like creating an object dynamically, means not =
the
object name but the class definition needs to be dynamically chosen, for
eg:- let me talk in C++ language=20
Class worker : public base
{
}
class clerk : public base
{
}
class manager : public base
{
}
// create an array of string
string emp[3] =3D {"worker","clerk","manager"};=20
some_func(int i)
{
base b* =3D new emp[i];
b->any_common_func();
}
--------------
This avoids lots of case statements, makes it easy to maintain and =
extend.=20
Any body has any idea how to implement it in C++(equivalent to =
Class.forname
in JAVA) If you have any other idea to accomplish this, also welcome.
Let me know if things are not clear.
Thanks
Somanathan
|