Reputation: 315
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
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