CarlJohnson
CarlJohnson

Reputation: 13

How can I do this easier?

Let's say I have two classes, a and b, and I have 2 objects, choice1 and choice2.

I ask the user to enter a number. If user enters 1, I will use choice1, otherwise choice2 if it is 2.

When I try to use the object which the user has chosen, I don't know how I will proceed because I don't know which object it is.

Is there a way I can manage this easier than what I did below?

int choice;
a choice1;
b choice2;
cout << "Enter 1 or 2";
cin >> choice;

if(choice == 1)
   choice1.setName("Carl");
else
   choice2.setName("Carl");

Upvotes: 0

Views: 45

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596527

In comments, you say that a and b have a common base class. In which case, setName() should be a member of that base class, and then you can do this:

base *b;
if (choice == 1)
    b = &choice1;
else
    b = &choice2;

/* alternatively:
base *b = (choice == 1) ? static_cast<base*>(&choice1) : static_cast<base*>(&choice2);
*/

b->setName("Carl");

If later on, you add more objects that also share this common base class, then consider using an array rather than a series of ifs, eg:

int choice;
a choice1;
b choice2;
c choice3;
...
base* choices[] = {&choice1, &choice2, &choice3};

cout << "Enter 1-3";
cin >> choice;

if ((choice >= 1) && (choice <= 3))
    choices[choice-1]->setName("Carl");

Upvotes: 1

Related Questions