RE: [Dev-C++] Help with creating objects dynamically
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Somanathan K. <som...@wi...> - 2003-07-22 08:36:43
|
Hi Marc,
Thanks for the suggestion. The switch statement is the one I want to
avoid in real time. As when the type of message (worker,clerk etc here)
more and more switch statements needs to be added. If you know the
working of Class.forname, you will get to know what I mean. One way I
can achieve this is by pooling the object(this is how normally people
does for real time saving) but would like to know there is an equivalent
to Class.forname. I will rewrite your code if C++ has Class.forname
#define PERSON_WORKER 1
#define PERSON_CLERK 2
#define PERSON_MANAGER 3
base* NewPerson(int nType)
{
return(base*) Class.forname(person_types[i];// person_types has array
of =20
//strings, say "worker, clerk etc. Please note
that //as and when the number
of types
//increased this line of code won't be
//changed but only the array index needs
//to be created
}
And then your function becomes:
some_func(int i)
{
base *b =3D NewPerson(i);
b->any_common_func();
}
Does it makes any sense?
somanathan
-----Original Message-----
From: Marc Heiligers [mailto:ma...@e-...]=20
Sent: Tuesday, July 22, 2003 1:42 PM
To: Somanathan Kaimal; dev...@li...
Subject: RE: [Dev-C++] Help with creating objects dynamically
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
|