Problem with constructor?

Hello and thank you for any help!

I don't understand why the objects are only out putting garbage. I've tried using pointers and char instead of strings and got the same results.

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
52
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>

using namespace std;

#ifndef INVOICE_H
#define INVOICE_H

class Invoice
{
private:
	string desc;
	int partNu;
	int quant;
	double price;
public:
	Invoice(int partNum, string descrip, int quant, double price)
	{
		partNum = partNu;
		descrip = desc;
		quant = 0;
		price = 0.0;
	}

	void setDesc(string d)
	{desc = d;}

	void setPart(int pn)
	{partNu = pn;}

	void setQuant(int q)
	{quant = q;}

	void setPri(double pr)
	{price = pr;}

	string getDesc() const 
	{return desc;}

	int getPart() const 
	{return partNu;}

	int getQuant() const 
	{return quant;}

	double getPri() const 
	{return price;}
};
#endif 


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
#include "stdafx.h"
#include "invoice.h"
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>

using namespace std;

int main()
{
	const int SIZE = 8;
	int in;

	Invoice invoices[] = {
		 Invoice( 83, "es", 7, 57.98 ),
         Invoice( 24, "ps", 18, 99.99 ),
         Invoice( 7, "sh", 11, 21.5 ),
         Invoice( 77, "h", 76, 11.99 ),
         Invoice( 39, "lm", 3, 79.5 ),
         Invoice( 68, "sd", 106, 6.99 ),
         Invoice( 56, "js", 21, 11 ),
		 Invoice( 3, "w", 34, 7.5 ) };

	
		 for (int i = 0; i < SIZE; i++)
		 {
		 cout << invoices[i].getPart() <<  invoices[i].getDesc() << invoices[i].getPart() << invoices[i].getPart() << '\n';
		 }

		 cin >> in ;


	return 0;
}
Let's begin at the top ^.^

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//invoice.h

#ifndef INVOICE_H    //put this
#define INVOICE_H  //at the beginning

//since you include all this stuff here
#include "stdafx.h"  
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>

using namespace std;

//main.cpp
//you don't have to include (actually it's bad that you do)all the stuff here again
#include "invoice.h"  //that's enough 


Next: I know it's a drag but define your class methods in a .cpp and not the header file
you'll learn one day why ;)

Okay next your problem (it's actually funny ^.^)

1
2
3
4
5
6
7
8
partNum = partNu;  //the first is your argument you pass to the constructor, the second your class field
// turn this around ^^:
partNu = partNum; // ;)
descrip = desc;  //same here
quant = 0; //here you use again your argument and not the class field
this->quant = 0;  //you can do it this way or rename it whatever 
price = 0.0;  //same here btw. you initialize them 0 and don't use the argument 
this->price = price; 


Have fun ^.^
Last edited on
Topic archived. No new replies allowed.