I am having a problem understanding this program. Mainly the purpose of line 41" void storeValues(InventoryItem&); // Receives an object by reference" . I'm not sure what they mean by "receives an object by reference". What is the difference between this and the line below it?
// This program passes an object to a function. It passes it
// to one function by reference and to another by value.
#include <iostream>
#include <iomanip>
#include <string>
usingnamespace std;
class InventoryItem
{
private:
int partNum; // Part number
string description; // Item description
int onHand; // Units on hand
double price; // Unit price
public:
void storeInfo(int p, string d, int oH, double cost); // Prototype
int getPartNum()
{ return partNum; }
string getDescription()
{ return description; }
int getOnHand()
{ return onHand; }
double getPrice()
{ return price; }
// Implementation code for InventoryItem class function storeInfo
void InventoryItem::storeInfo(int p, string d, int oH, double cost)
{ partNum = p;
description = d;
onHand = oH;
price = cost;
}
// Function prototypes for client program
void storeValues(InventoryItem&); // Receives an object by reference
void showValues (InventoryItem); // Receives an object by value
int main()
{
InventoryItem part; // part is an InventoryItem object
storeValues(part);
showValues(part);
system("pause");
return 0;
}
void storeValues(InventoryItem &item)
{
int partNum; // Local variables to hold user input
string description;
int qty;
double price;
// Get the data from the user
cout << "Enter data for the new part number \n";
cout << "Part number: ";
cin >> partNum;
cout << "Description: ";
cin.get(); // Move past the '\n' left in the
// input buffer by the last input
getline(cin, description);
cout << "Quantity on hand: ";
cin >> qty;
cout << "Unit price: ";
cin >> price;
// Store the data in the InventoryItem object
item.storeInfo(partNum, description, qty, price);
}
void showValues(InventoryItem item)
{
cout << fixed << showpoint << setprecision(2) << endl;;
cout << "Part Number : " << item.getPartNum() << endl;
cout << "Description : " << item.getDescription() << endl;
cout << "Units On Hand: " << item.getOnHand() << endl;
cout << "Price : $" << item.getPrice() << endl;
}
By reference means that you pass the original object. By value means that you pass a copy of the original object.
What's the difference? Modifying a variable which was "passed by reference" will modify the variable in the calling function. It can be treated as a second output from a function. Another advantage is that it doesn't copy data when the function is called which can save a lot of time for big containers.
#include <iostream>
usingnamespace std;
int plus1A(int i)
{
i++;
return i;
}
int plus1B(int& i)
{
i++;
return i;
}
int main()
{
int a = 1;
int b = plus1A(a);
cout << "a = " << a << " b = " << b << endl;
int c = 1;
int d = plus1B(c);
cout << "c = " << c << " d = " << d << endl;
}