account code


There seems to be problem when giving total value junk value is stored even when itialised can anyone tell me whats the probelm


#include"Gradebook.h"
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;

Gradebook::Gradebook( int balance)
{
if(balance>=0)
{
balance=balance;
Withdraw(balance);
}
else
{
cout<<"Balance can not be negative\n";
}

}
void Gradebook::Withdraw(int)
{
cout<<"Enter amount to withdraw\n";
cin>>credit;
if(balance>credit)
{
cout<<"invalid credit greater than balance\n";
}
if (balance<credit)
{
int total=balance-credit;

cout<<"Current balance:"<<total;
}
getch();
}


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
#include<string>
#include<iostream>
using namespace std;


class Gradebook
{
public:

Gradebook(int balance);
void Withdraw(int);
private:
	int credit;
    int balance;
	int total;
};









#include"Gradebook.h"
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{

	cout<<"Enter intial amount\n";
	int intialamount;
	cin>>intialamount;
	Gradebook myGradebook(intialamount);
	

}



	



You can't give a parameter the same name as a member variable like that without confusion. The compiler doesn't know which "balance" you're referring to.

Alter it so that when you're referring to the member variable, you use the this-> prefix.

In situations where there is less logic in the constructor, don't forget that you can use initialisation lists. One of the advantages of this is that the compiler can distinguish between similarly named variables, so you don't need the this keyword.

Generally speaking, I don't think you want such logic in the constructor. It's for the creation of the object. In this case, I'd consider it for initialising any members and not much else.
Last edited on
1. you do not need to have these three variables in the class level,
int credit;
int balance;
int total;
2. do not forget to initialize any variables, if you are using an old compiler.
Thanks iHutch that was the exact problem
Topic archived. No new replies allowed.