I was testing out a small program on hierarchical inheritance when I encountered this problem. This program contains a parent class Bank, and two child classes Withdraw & Deposit.
#include<iostream>
#include<conio.h>
#include<stdlib.h>
//Hierarchical Inheritance
using namespace std;
class bank{
protected:
char name[20];
int age, id;
float bal;
public:
void getData(){
cout <<"Enter your name, age, bank ID and balance" << endl;
cin >> name >> age >> id >> bal;
}
void display(){
cout <<"Name: " << name << endl << "ID: " << id << endl;
cout <<"Age: " << age <<endl <<"Balance: " << bal << endl;
}
void check(){
cout <<"Your balance is " << bal << endl;
}
};
class withdraw : public bank{
float wd;
public:
void withdrawMoney(){
cout << "Enter the amount to withdraw" << endl;
cin >> wd;
if(wd > bal)
cout << "You cannot withdraw that much. Your balance is only " << bal << endl;
else{
bal = bal-wd;
cout << "You successfully withdrew " << wd << ". Your remaining balance is " << bal << endl;
}
}
};
class deposit : public bank{
float dp;
public:
void depo(){
cout <<"Enter the amount to deposit" << endl;
cin >> dp;
bal = bal+dp;
cout <<"You successfully deposited " << dp << ". Your balance is now " << bal << "." << endl;
}
};
int main()
{
int c;
bank b;
deposit d;
withdraw w;
b.getData();
do{
cout <<"***The Dank Bank***" << endl;
cout <<"What do you want to do?\n 1)Withdraw\n 2)Deposit\n 3)Check Balance\n 4)Display all details\n 5)Exit\n" << endl;
cin >> c;
if(c == 1)
w.withdrawMoney();
else if (c == 2)
d.depo();
else if(c == 3)
b.check();
else if(c == 4)
b.display();
else if(c == 5)
exit(0);
else
cout <<"Wrong choice." << endl;
cout<<"Press any key to continue" << endl;
getch();
}
while(1);
getch();
return 0;
}
When carrying out the withdraw function, I get this output:
You cannot withdraw that much. Your balance is only 6.03937e-039
When using the deposit function, the output shows the deposited amount instead of the actual balance.
You successfully deposited 1000. Your balance is now 1000.
The only variable used by both the child classes was bal, so I decided to declare it globally like this.
#include<iostream>
#include<conio.h>
#include<stdlib.h>
float bal;
The program worked without any flaws. But doing this defeats the whole purpose of using inheritance.
I'm confused. Why is this happening?