I’ve got a homework assignment where I have a base class Package, and two derived classes, OvernightPackage and TwoDayPackage. At one point in the problem I need to create an object of one of those two types, depending on user input. This obviously doesn’t work:
if (shippingOption == OVERNIGHT) {
OvernightPackage packageObject( // Parameters entered here //);
}
else if (shippingOption == TWODAY) {
TwoDayPackage packageObject( // Parameters entered here //);
}
Once those if statements execute, I’m out of the scope of those objects, and can’t use packageObject. This post helped me understand how I could do it if I was just creating an object of a certain type with different parameters. But the requirements on the assignment are that TwoDayPackage and OvernightPackage need to be different classes.
How would I go about doing this (besides just doing what I need to with the objects in the if statements)?
EDIT: Thanks for helping clear things up, everyone!
One way is to use pointers: