How to change the member value of a struct object? (C++ struct beginner)
Solution 1
First, try searching google for "passing parameters by reference and by value".
You'll learn that:
void readEmpoyeeRecord(Employee staff);
passes your variable to the function by value, meaning that a copy of your object is created and used inside the function, so your original object doesn't get modified, but a copy.
To get the desired result, use:
void readEmpoyeeRecord(Employee& staff);
Passing by reference means you pass that exact same object, and not a copy.
Your code will basically work like this:
//create new employee
Employee employeeA;
//call method readEmployeeRecord on a copy of employeeA
readEmpoyeeRecord(employeeA);
//call method printEmployeeRecord on a copy of employeeA
printEmployeeRecord(employeeA);
Solution 2
readEmpoyeeRecord(Employee employee)
is copy by value, not reference, so you are loosing your changes.
Use readEmpoyeeRecord(Employee& employee)
instead.
Solution 3
Your problem is that in C++, objects are passed by value until you specify otherwise. Thus, in the body of readEmpoyeeRecord
you're dealing with a copy of employeeA
, not with employeeA
itself.
Pass a reference to your readEmpoyeeRecord
function. The signature of readEmpoyeeRecord
should read:
void readEmpoyeeRecord(Employee &employee)
Holly
Updated on June 28, 2022Comments
-
Holly almost 2 years
Just beginning to learn about structs, I thought I understood how they work, using the dot operator to access a member of an object, but i clearly don't as the readEmployeeRecord function below doesn't work at all. How should i be doing this? (the code is short and self explantory)
Many thanks for taking the time to further explain structs to me! Naturally I tried google first but i couldn't find an example that inputted data quite the way i wanted and wasn't sure how i should be going about it.
#include <iostream> #include <iomanip> using namespace std; //Employee type struct Employee{ float wage; char status; char dept[4]; //for 3letter department, last position is \0 correct? }; //function definitions void readEmpoyeeRecord(Employee staff); void printEmployeeRecord(Employee staff); int main(){ Employee employeeA; readEmpoyeeRecord(employeeA); printEmployeeRecord(employeeA); return 0; } void readEmpoyeeRecord(Employee employee){ cout << "Enter empolyees wage: "; cin >> employee.wage; cout << "Enter empolyees status (H or S): "; cin >> employee.status; cout << "Enter empolyees dept (ABC): "; cin >> employee.dept; } void printEmployeeRecord(Employee staff){ cout << "Wage: Status: Department:" <<endl; cout << fixed << setprecision( 2 ) << staff.wage; }