calling cunstroctor from CString object

N

NightCrawler

Hi
can i call a constructor of a class, if the name is stored in a CString
Object
e.g.

class CBaseClass
{
int x;
};

class CDerClass1: public CBaseClass
{
int y;
};

class CDerClass2: public CBaseClass
{
int z;
};

CString strClassName;
// = L"CMyClass";//using unicode charset....

//main1//i know this


CBaseClass* pPtr;
------
----
----------

if(some condition)
{
strClassName = L"CDerClass1"
pPtr = new CDerClass1;
}
else
{
strClassName = L"CDerClass2"
pPtr = new CDerClass2;
}
//for 2 classes this approach is fine but
//what if i have more than 100 classes derived from the same class
//n at runtime i want to allocate the memory for them.....

//main2//can it be done????


CBaseClass* pPtr;
------
----
----------

if(some condition)
{
strClassName = L"CDerClass1"
}
else
{
strClassName = L"CDerClass2"
}
//now i want to allocate the memory for the class whose name is stored
in the strClassName
pPtr = new "some way to call the constructor whose name is stored in
string.....";


plz help me i m tired of writting this if else statements........
 
?

=?iso-8859-1?q?Erik_Wikstr=F6m?=

Hi
can i call a constructor of a class, if the name is stored in a CString Object

What you want is called reflection, and it's not available in C++.
However if you sit down and think you'll probably be able to come up
with a solution that does not require such a thing by redesigning your
application.
 
S

Satish

if(some condition)
{
strClassName = L"CDerClass1"
}
else
{
strClassName = L"CDerClass2"
}
//now i want to allocate the memory for the class whose name is stored
in the strClassName
pPtr = new "some way to call the constructor whose name is stored in
string.....";

Any way you need to do this if, else checking to determine the class
name.

Instead of setting strClassName variable, you can set an
enumeration/int variable have a switch case

Check out here
http://home.earthlink.net/~huston2/dp/FactoryMethodDemosCpp

Not sure how much this helps but this is how I would have done.

Thanks,
 

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,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top