I know we can do the following with heap objects:
/* Heap objects */
Pet *pet;
if (...)
pet = new Pet("Dog");
else
pet = new Pet("Cat");
But how do we do it if we wanted the Pet object to be declared on the stack?
/* Stack objects */
Pet pet;
if (...)
-?-
else
-?-
Try the following
Pet pet(theCondition ? "Dog" : "Cat");
Or if the conditional blocks are more complex than a single initialization store the const char* which is used for initialization as a separate local
const char* pArgument;
if (...) {
...
pArgument = "Dog";
} else {
...
pArgument = "Cat";
}
Pet pet(pArgument);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With