Page 307 - Computer_Science_F5
P. 307
Computer Science Developing program using polymorphism to calculate areas for various
Activity 4.11:
shapes
FOR ONLINE READING ONLY
Develop a program using polymorphism to calculate the areas of a rectangle,
square, trapezium, and rhombus.
Encapsulation in C++
Program Example 4.44:
Program code demonstrating encapsulation
#include <iostream>
using namespace std;
// Class definition
class BankAccount {
private: // This shows data members are private, therefore, encapsulated
string accountHolderName;
double balance;
public: // This shows member functions are public
// Constructor
BankAccount (string name, double initialAmount) {
accountHolderName = name;
balance = initialAmount;
}
// This method will deposit money
void deposit (double amount) {
balance += amount;
}
// This method will withdraw money
void withdraw (double amount) {
if (amount <= balance) {
balance -= amount;
} else {
cout << “No enough cash!” << endl;
}
}
// This method will display account information
298
for Advanced Secondary Schools
Computer Science Form 5.indd 298 23/07/2024 12:34

