CSC166 Object Oriented Programming

Object Oriented ProgrammingTU Board 2078

Write a program according to the specification given below: – Create a class Account with data members acc no, balance, and min balance(static) Include methods for reading and displaying values of…

10

Write a program according to the specification given below:

  • – Create a class Account with data members acc no, balance, and min_balance(static)
  • -Include methods for reading and displaying values of objects
  • – Define static member function to display min_balance
  • -Create array of objects to store data of 5 accounts and read and display values of each object

Answer

A static data member is shared by all objects of the class, and is defined once outside the class. A static member function can be called with the class name and can access only static members.

#include <iostream>
using namespace std;

class Account {
    int acc_no;
    float balance;
    static float min_balance;          // shared by all accounts
public:
    void read() {
        cout << "Account number: ";
        cin >> acc_no;
        cout << "Balance: ";
        cin >> balance;
    }

    void display() const {
        cout << "Account " << acc_no << "  Balance: Rs. " << balance << endl;
    }

    static void showMinBalance() {      // static member function
        cout << "Minimum balance: Rs. " << min_balance << endl;
    }
};

float Account::min_balance = 1000;     // definition of the static member

int main() {
    Account acc[5];                    // array of 5 objects

    for (int i = 0; i < 5; i++) {
        cout << "\nEnter details of account " << i + 1 << endl;
        acc[i].read();
    }

    cout << "\n--- Account details ---\n";
    for (int i = 0; i < 5; i++)
        acc[i].display();

    Account::showMinBalance();         // called with the class name
    return 0;
}

Explanation

  • min_balance is declared static inside the class and defined once outside it, so one copy is shared by all five accounts.
  • showMinBalance() is a static member function, so it is called as Account::showMinBalance() without any object.
  • acc[5] is an array of objects; read() and display() are called on each element in a loop.

Discussion

Loading…

More Object Oriented Programming questions

All Object Oriented Programming old questions