default constructor

heeey guys,
i was writing this code and i dont know why is the default constructor not initializing the members of the class to zero. can anyone help me?
thank you a lot !!

this is the header file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 #ifndef PURSE_H
#define PURSE_H

#include <iostream>
using namespace std;

class Purse {
public:

	int hundreds;
	int fifties;
	int twenties;
	int tens;
	int ones; 
	int halves; 
	int quarters;

	Purse ();
	Purse (double money);
};
#endif 


this is the c++ file

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
53
54
55
56
57
58
#include "purse.h"

Purse :: Purse () {

	hundreds = 0;
	fifties = 0;
	twenties = 0;
	tens = 0;
	ones = 0; 
	halves = 0; 
	quarters = 0;

}
Purse :: Purse (double money){

	hundreds = 0;


	while (money>0){
	
		if ((money-100)>0){
		
			money = money - 100;
			hundreds++;
		}
		else if ((money-50)>0){
	
			money = money - 50;
			fifties++;
		}
		else if ((money - 20)>0){
		
			money = money - 20;
			twenties++;
		}

		else if ((money-10)>0){
		
			money = money - 10;
			tens++;
		}
		else if ((money-1)>0){
		
			money = money - 1;
			ones++;
		}
		else if ((money-0.5)>0){
		
			money = money - 0.5;
			halves++;
		}
		else if ((money-0.25)>0){
		
			money = money - 0.25;
			quarters++;
		}
	}
}


this is my main :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "purse.h"
#include <iostream>
using namespace std;

int main (int argc, char ** argv){

	double m;

	cout << " please enter the amount of money " << endl;
	cin >> m;

	Purse p ();
	Purse purse (m);

	return 0;
}
What makes you think it doesn't?
because i used the debugger to check the code i wrote
Only 1 constructor gets called per object.

If you are creating the object like this:

Purse purse (m);

Then that means this ctor: Purse :: Purse (double money){ is being called INSTEAD OF the default ctor (not in addition to)

EDIT:

This means that since you are only resetting the vars to zero in the default ctor... they will only be set to zero when the default ctor is used.


Also... on a side note:
1
2
Purse p (); // <- this is wrong.  This is declaring a function
Purse p;  // <- this is right.  Don't use parenthesis here 

Last edited on
uhhhh okey now i get it :) thank you :)
EDIT: Not to answer your question, just something additional which you'll encounter when trying to make a class contain a reference or const field.

This is assignment.

1
2
3
4
5
6
7
8
9
10
Purse :: Purse ()
{
	hundreds = 0;
	fifties = 0;
	twenties = 0;
	tens = 0;
	ones = 0; 
	halves = 0; 
	quarters = 0;
}



This is initialization. Which I believe is faster than assignment.

1
2
3
4
5
6
7
8
9
10
Purse :: Purse ()
: // Note the : here!
	hundreds(0),
	fifties(0),
	twenties(0),
	tens(0),
	ones(0), 
	halves(0), 
	quarters(0)
{}
Last edited on
Topic archived. No new replies allowed.