-4

I'm relatively new to C++. I'm using a function to give an object some values, but I keep getting the error that the object is being used without being initialized. How come?

The definition of Worker:

class Worker 
    public:
    int telephone;
    char firstname[20];
    char task[100];
    int salary;
    int id;
};

The actual code:

Worker worker1;
worker1 = getWorker(worker1);

Worker getWorker(Worker worker){
    cout << "First name: ";
    cin >> worker.firstname;
    return worker;
Jullix993
  • 105
  • 10

2 Answers2

1

getWorker doesn't need an argument. Use a local object to get the input, and return it:

Worker getWorker() {
    Worker worker;
    // whatever
    return worker;
}

Also, use initialization instead of creating objects then assigning to them. Like this:

Worker worker1 = getWorker();
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

As you haven't explicitly set the value of firstname there could be any kind of garbage stored in the 20 bytes that make up firstname. char buffers are 0 terminated, so best practice would be to give an initial value to firstname in a default constructor:

Worker(){
  //omitting other code
  firstname[0] = '\0';
}

Of course, if you want the variable to hold an actual value it would be best to pass it into the constructor.

Lloyd Crawley
  • 606
  • 3
  • 13