RE: [Dev-C++] Help with creating objects dynamically
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: xRxIxPx <xr...@gm...> - 2003-07-21 16:39:42
|
At 16:36 2003-07-21 +0530, Somanathan Kaimal wrote:
>This is a strange requirement. Name of the object is normally irrelevant=20
>compared to its definition. Do you mind in sharing your requirement?
>
>
>-----Original Message-----
>From: OROSZI Bal=E1zs [mailto:or...@vp...]
>Sent: Monday, July 21, 2003 4:26 PM
>To: dev...@li...
>Subject: Re: [Dev-C++] Help with creating objects dynamically
>
>Satish Medepalli wrote:
> > I have the following requirement while creating objects.. I will try=
to
> > explain it using a small example..
> >
> > Suppose I have a class Student defined and I want to create objects=
of
> > type Student inside the main function..
> >
> > And say, the actual name with which i want to create the obect is
> > stored in a character array at run time.. say i have the following
> > statement
> > char NAME[]=3DgetName();
> > and the above function is returning the name "JOHN" at run time.
> >
> > Now i want to get the name out of the character array and create the
> > object using that particular name at run time.. i.e.,
> > Student JOHN;
> >
> > in a nutshell i want to give the name of the objects to be created at
> > run time. IS THIS POSSIBLE?? IF SO CAN ANYONE HELP ME WITH THIS??
>
>Nope. As far as I know, this is not possible in C++. I know, that Perl
>can do it, but if you EVER programmed in Perl, you know how different it
>is. So I don't think it ca nbe done.
>
>A solution to your problem might be to give a "name" member to your
>class, then at object creation, the constructor takes it as parameter,
>and copies it into the name member.
Should work.
Well better: use a map. Something like this should work, though not tested=
=20
right now.
STL is a wonderful tool.;)
#include <map>
#include <string>
#include "MyObjectClass.h"
//and then have you object database
std::map<std::string, MyObjectClass*> obj_db;
void add_to_db()
{
MyObjectClass* obj =3D new MyObjectClass;
obj_db.insert(std::map<std::string, MyObjectClass*>::value_type(=20
std::string(getName()), obj));
}
MyObjectClass& get_from_db(const std::string& name)
{
std::map<std::string, MyObjectClass*>::iterator it;
it =3D obj_db.find(name);
if (it =3D=3D map.end()) throw std::string("name not found int=
obj_db");
return *it;
}
|