Home > database >  C how to call a method from a class chosen by user input
C how to call a method from a class chosen by user input

Time:04-04

So i have an assignment and im evaluating this as a "maybe its a solution", but i dont know if this is possible so you tell me...

Lets say we have this class

class Person
{
  private:
  string name;
  int number;
  public:
  Person(string n, int num)
  {
    name = n;
    number = num;
  }
  void greeting()
  {
    std::cout<<"hello my name is"<<this->name<< "and my number is"<<this->number;
  }
}

And we have multiple persons in the main, and i want the user to input the name of a person and then the person with that name to call its greeting method.

Like this: (its just an idea to frame the question better, it obviously wont compile)

int main(){
//assume lots of person objects are already declared, and the inuput name corresponds to an existent person and so on... 
Person person;
std::cin>>person;
person.greeting();
}

¿so is that idea in c possible?

note: this is not my actual assingment, its just a simplificated way to illustrate my question.

Thank you for your time.

CodePudding user response:

I think you want a map, your constructor was wrong too

class Person
{
private:
    string name;
    int number;
public:
    Person(string n, int num)
    {
        name  = n;
        number = num;
    }
    void greeting()
    {
        std::cout << "hello my name is" << this->name << "and my number is" << this->number;
    }
};
int main() {
    string person;
    std::map<string, Person> people;
    people.emplace(std::make_pair("Anne", Person("Anne", 42)));
    people.emplace(std::make_pair("Dave", Person("Dave", 42)));
    std::cin >> person;
    auto look = people.find(person);
    if (look != people.end()) { // did we find them?
        look->second.greeting();
    }
}

CodePudding user response:

You'll want to use a hash table map. Or more precisely, std::unordered_map

int main()
{
    Person *selbie = new Person("selbie", 8675309);
    Person *tomas = new Person("Tomas", 4441212);
    Person *joe= new Person("Joe", 3218890);

    std::unordered_map<string, Person*> peopleMap;

    peopleMap["selbie"] = selbie;
    peopleMap["tomas"] = tomas;
    peopleMap["joe"] = joe;

    
    std::string name;
    std::cin >> name;

    auto itor = peopleMap.find(name);
    if (itor != peopleMap.end())
    {
        People* personOfInterest = itor->second;
        personOfInterest->greeting();
    }

    // don't forget to cleanup all your objects when done
    delete selbie;
    delete tomas;
    delete joe;

}
  • Related