Sarathi Shah
Sarathi Shah

Reputation: 315

can we create object of class based on condition statement?

I am creating a bank program where if acc_type is current then obj should be created of currentclass(derived from bank class) or else object should be created of savingclass(derived from bank class).can i use like this?i used it but it is showing error somelike 'obj' was not declared in the scope.enter image description here

if(condition)
{
    derivedclass1 obj; //first object
}
else
{
    derivedclass2 obj; //second object
}    

Upvotes: 0

Views: 1063

Answers (1)

Ken Y-N
Ken Y-N

Reputation: 15009

The simple solution is:

baseclass *obj;
if(condition)
{
    obj = new derivedclass1; //first object
}
else
{
    obj = new derivedclass2; //second object
}

There's other ways of doing this (I'd personally use a std::unique_ptr), but this is the easiest to understand.

Upvotes: 1

Related Questions