Class member functions returning wrong answer?

I'm wanting the program to display "12: 4" (item number: total cost)

but it is displaying "-858993460: 7.95081e+070"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
  #include <iostream>
using namespace std;

class inventory {
	public:
		inventory(){
			itemNumber = 0;
			quantity = 0;
			cost = 0;
		}
		inventory(int n, int q, double c){
			n = getItemnumber();
			q = getQuantity();
			c = getCost();
			cout << n << ": " << getTotalcost(q, c) << "\n\n";
		}
		void setItemnumber(int theItemnumber){
			itemNumber = theItemnumber;
		}
		void setQuantity(int theQuantity){
			quantity = theQuantity;
		}
		void setCost(int theCost){
			cost = theCost;
		}
		int getItemnumber(){
			return itemNumber;
		}
		int getQuantity(){
			return quantity;
		}
		double getCost(){
			return cost;
		}
		double getTotalcost(int iQuan, double iCost){
			return iQuan * iCost;
		}

	private:
		int itemNumber, quantity;
		double cost;
};

int main()
{
	

	inventory theInventory(12, 2, 2);

	return(0);
}
1
2
3
4
5
6
		inventory(int n, int q, double c){
			n = getItemnumber();
			q = getQuantity();
			c = getCost();
			cout << n << ": " << getTotalcost(q, c) << "\n\n";
		}


This constructor never initializes your itemNumber, quantity, or cost members. As a result, your getxxx() functions are all returning uninitialized variables which are filled with garbage.

It also doesn't make sense to assign local variables 'n', 'q', and 'c'. By doing that you are effectively throwing away what is passed to the constructor.

You probably just have your assignments backwards:

1
2
3
4
5
inventory(int n, int q, double c)
{
    itemNumber = n;  // assign itemNumber... not n
    quantity = q;  // ditto
    cost = c;  // ditto 
Wow! Thank you so much for the great explanation! Been going crazy because of this!
Topic archived. No new replies allowed.