>> ... depending on the value of variable "var"at runtime. Also i know it can be done using template ...
an option would be to use run-time polymorphism.
class base { virtual ~base() = 0 {} };
class Class1 : public base {} ;
class class2 : public base {} ;
base* createandmanipulate( ifstream& file );
int main()
{
//....
//.....
base* object = createandmanipulate(file);
if( var==true )
{
class1* c1 = dynamic_cast<class1*>(object) ;
assert(c1) ;
// use c1
}
else
{
class2* c2 = dynamic_cast<class2*>(object) ;
assert(c2) ;
// use c2
}
//....
//.....
delete base ;
}
use an if/else with dynamic cast only if virtual functions cannot meet your requirements.
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
>>an option would be to use run-time polymorphism.
I thought about that too but dismissed it because it may not work. createandmanipulate() still has to know whether to allocate an object of type Class1 or Class2 before returning. If it allocates an object of only base then the caller will not get what it expects.
Ancient Dragon
Retired & Loving It
30,042 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,341
>> If it allocates an object of only base
base has a pure virtual destructor, the function will not be able to instantiate (a standalone) object of that type.
however, it could return 0; perhaps indicating an error of some kind.
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287