RE: [Dev-C++] Help with creating objects dynamically
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Jaap de W. <wo...@ne...> - 2003-07-22 07:10:57
|
Below is a piece of code what is creating named objects dynamicaly.
Is that what you mean?
> -----Original Message-----
> From: Satish Medepalli [mailto:sat...@ya...]
> Sent: Monday, July 21, 2003 6:28 AM
> To: dev...@li...
> Subject: [Dev-C++] Help with creating objects dynamically
>
>
> Hello,
>
> 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[]=getName();
> 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??
>
> Thank You in advance.
> -Sateesh Medepalli
>
=================================== start of code
===================================
#include <list>
#include <string>
#include <iostream>
class Object
{
public:
std::string &GetName(){return m_name;}
virtual std::string &GetFunction()=0;
protected:
Object(const char *name):m_name(name){}
Object(const Object &src):m_name(src.m_name){}
private:
std::string m_name;
friend std::ostream &operator <<(std::ostream &os, Object& ol);
};
class Student: public Object {
public:
virtual std::string &GetFunction(){return m_function;}
Student(const char *name):Object(name) {}
Student(const Student& src):Object(src) {}
private:
static std::string m_function;
};
class Teacher: public Object {
public:
virtual std::string &GetFunction(){return m_function;}
Teacher(const char *name):Object(name) {}
Teacher(const Teacher& src):Object(src) {}
private:
static std::string m_function;
};
std::string Student::m_function ("Student");
std::string Teacher::m_function ("Teacher");
class ObjectList: public std::list<Object *>
{
public:
~ObjectList();
};
ObjectList::~ObjectList()
{
iterator i;
for (i = begin(); i != end(); i++)
{
delete *i;
}
}
std::ostream &operator <<(std::ostream &os, Object& ob)
{
return os << ob.m_name << " (" << ob.GetFunction() << ")";
}
std::ostream &operator <<(std::ostream &os, ObjectList& ol)
{
ObjectList::iterator i;
for (i = ol.begin(); i != ol.end(); i++)
{
os << **i << std::endl;
}
return os;
}
void main()
{
ObjectList AllPeople;
AllPeople.push_back(new Student("Jan"));
AllPeople.push_back(new Student("Piet"));
AllPeople.push_back(new Student("Klaas"));
AllPeople.push_back(new Teacher("Jan"));
AllPeople.push_back(new Teacher("Mark"));
std::cout << AllPeople;
}
|