Operator Overloading Programming Exercise 2

Operator overloading defines an additional meaning of operator.

Operator overloading is a feature of C++ programming language that allows a programmer to redefine the meaning of operator when they operate on class object.

If you don’t familiar with operator overloading please read the following article first.

What is Class?

Class may be defined as the collection of objects which have some properties and functions.

If you want to know more about classes, please read the following article.

Question Number 2

Define a class for a bank account that includes the following data members:
1. Name of the depositor
2. Account Number
3. Type of account
4. Balance amount in the account
The class also contains the following member functions:
A. A constructor to assign initial values
B. Deposit function to deposit some amount. It should accept the amount as parameter.
C. Withdraw function to withdraw an amount after checking the balance. It should accept the amount as parameter.
D. Display function to display name and balance.
E. Overload binary +operator that adds the balance of one account to another account. It should accept an object as parameter and add the values of the parameter to the calling object.


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

 class bank
 {
 	private:
 		char name[20];
 		int acno;
 		char actype[20];
 		int bal;
 		public:
 			bank();
 			void deposit(int amt);
 			void withdraw(int amt);
 			void display();
 			void add(bank ac);
 };
   bank::bank()
  {
  	cout<<"Enter account name: ";
  	gets(name);
  	cout<<"Enter account no: ";
  	cin>>acno;
  	cout<<"Enter account type: ";
  	gets(actype);
  	cout<<"Enter opening balance: ";
  	cin>>bal;
  }
  void bank::deposit(int amt)
  {
  	bal = bal + amt;
  	cout<<"\nBalance after deposit: "<<bal;
  }
  void bank::withdraw(int amt)
  {
  	if(amt > bal)
  	cout<<"Not enough amount in account! "<<endl;
  	else
  	{
  		bal = bal - amt;
  		cout<<"Balance after withdraw: "<<bal;
  	}
  }
  void bank::display(void)
  {
  	cout<<"Account Details: "<<endl;
  	cout<<"Account Name:   "<<name<<endl;
  	cout<<"Account No.   "<<acno<<endl; 
  	cout<<"Account Type:   "<<actype<<endl;
  	cout<<"Current Balance:   "<<bal<<endl;
  }
  void bank::add(bank ac)
  {
  	bal = bal + ac.bal;
  }
   main()
   {
   	bank x, y;
   	x.add(y);
   	x.display();
   }

Leave a Reply