Home > OS >  How to create objects based on user input?
How to create objects based on user input?

Time:10-04

I want to make a program which creates an object each time user enters an employee name. The object should be named according to the name of the employee.

#include <iostream>
using namespace std;

class employee
  {
    public:
    
    int salary;
    int  ma = 300;
    float da = 1.25;
    float hra = 0.15;
    
  };
int main()
{
  char name;
  cin >> name;
  employee:("name");
}

How can do this? using this piece of code throws an error

main.cpp:18:13: warning: expression result unused
      [-Wunused-value]
  employee:("name");
            ^~~~~~
1 warning generated.

CodePudding user response:

Give the employee class a name field, and a constructor to initialize it

#include <iostream>
#include <string>
using namespace std;

class employee
{
public:
    string name;
    int salary = 0;
    int ma = 300;
    float da = 1.25;
    float hra = 0.15;

    employee(string name) : name(name) {}
};

int main()
{
    string name;
    cin >> name;
    employee emp(name);
}
  • Related