Click here to Skip to main content
16,007,126 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i wnt to know the use of constructor initialization to 0(zero) as in the following program

What I have tried:

when I run the following program, sa is always 0 which should not be


C++
class bank
{
private:
double a,sa;
char ac,c,s;
public:

void deposit(double amount, char account);
};
void bank::deposit(double amount, char account)
{
a=amount,
ac=account;
if (ac=='s')
{
sa=sa+a;
cout<<sa;

}
}
main()
{
char account;
double amount;

clrscr();
bank b;
cout<<"enter account type: ";
cin>>account;
cout<<"enter amount:" ;
cin>>amount;
b.deposit(amount, account);
getch();
}

but when i add
C++
/*bank()
{
sa=0;
}*/

as in the following program, it shows correct sa i.e. the following program shows the correct result.
C++
class bank
{
private:
double a,sa;
char ac,c,s;
public:
bank()
{
sa=0;
}
void deposit(double amount, char account);
};
void bank::deposit(double amount, char account)
{
a=amount,
ac=account;
if (ac=='s')
{
sa=sa+a;
cout<<sa;

}
}
main()
{
char account;
double amount;

clrscr();
bank b;
cout<<"enter account type: ";
cin>>account;
cout<<"enter amount:" ;
cin>>amount;
b.deposit(amount, account);
getch();
}


so,
can anyone enlighten me, what is the use of:-
C++
bank()
/*{
sa=0;
}*/
Posted
Updated 19-Jan-17 21:29pm
v3

It is called data member initialization and is the very purpose of constructors (they should set the initial staate of the object).
A not initialized data member may contain garbage.
 
Share this answer
 
Comments
Member 12959299 20-Jan-17 8:05am    
thank u sir/mam
CPallini 20-Jan-17 8:19am    
You are welcome.
The value in an unassigned variable is undefined.
So when you say double sa; the value in sa will be whatever is left over in the memory allocated to it.

When you create a constructor and do assignment, the value is set to 0.

So the way you have shown the constructor, translates to -
double sa;
sa = 0;
 
Share this answer
 
Comments
Member 12959299 20-Jan-17 8:04am    
thank u sir/mam

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900