Saturday 17 September 2011

Constructor overloading


Ex.No:6
Constructor overloading
Aim:
To write a C++ program to display the account number and balance using constructor overloading.
Algorithm:
Step 1: Create a class as Account.
Step 2: Declare the data members as accountid and balance.
Step 3: Declare the member functions as
void Account() implies default constructor
void Account(float) implies one argument constructor
void Account(int,float) implies two argument constructor
void moneytransfer(Account,float)
void display()
Step 4: In main, create the object for Account class.
Step 5: While creating the object without argument, the default constructor is called.
Step 6: While creating the object with one argument, constructor with one argument is
called and value is assigned to the accoundid.
Step 7: Call the display() function to display the account details.
Step 8: While creating the object with two arguments, constructor with two arguments is
called and value is assigned to the accoundid and balance.
Step 9: Call the display() function to display the account details.
Step 10: Call the money transfer() function to transfer the money and display the balance
after money transfer.
Program:
#include<iostream.h>
#include<conio.h>

class Account
{
int accid;
float balance;
public:
Account();
Account(float );
Account(int ,float);
void moneytransfer(Account&,float);
void display();
};

Account::Account()
{
accid=1;
balance=1000.0;
}

Account::Account(float y)
{
accid=2;
balance=y;
}

Account::Account(int x,float z)
{
accid=x;
balance=z;
}

void Account::display()
{
cout<<"\t"<<accid;
cout<<"\t\t"<<balance<<"\n";
}

void Account::moneytransfer(Account &ac1,float amount)
{
ac1.balance=ac1.balance+amount;
balance=balance-amount;
}

void main()
{
clrscr();

float a;
cout<<"\nEnter the amount to be transfer:";
cin>>a;

Account ac1;
Account ac2(25000);
Account ac3(3,45000);

cout<<"\n\nBefore Money Transfer:\n";
cout<<"\tAccountID\tAmount\n";
ac1.display();
ac2.display();
ac3.display();

ac3.moneytransfer(ac1,a);

cout<<"\n\n After Money Transfer:\n";
cout<<"\tAccountID\tAmount\n";
ac1.display();
ac2.display();
ac3.display();
}

Output:

Enter the amount to be transfer:500

Before Money Transfer:
        AccountID       Amount
        1               1000
        2               25000
        3               45000

 After Money Transfer:
        AccountID       Amount
        1               1500
        2               25000
        3               44500

0 comments:

Post a Comment