Problem Statement 1: Shape Inheritance (C++)
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
public:
virtual double area() = 0;
};
class Rectangle : public Shape {
double length, width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
double area() {
return length * width;
}
};
class Circle : public Shape {
double radius;
public:
Circle(double r) {
radius = r;
}
double area() {
return M_PI * radius * radius;
}
};
int main() {
Rectangle r(10, 5);
Circle c(7);
cout << "Rectangle Area: " << [Link]() << endl;
cout << "Circle Area: " << [Link]() << endl;
return 0;
}
Terminal Output:
$ g++ [Link] -o shape
$ ./shape
Rectangle Area: 50
Circle Area: 153.938
Problem Statement 2: Account Inheritance (C++)
#include <iostream>
using namespace std;
class Account {
protected:
string accountNumber;
double balance;
public:
Account(string acc, double bal) {
accountNumber = acc;
balance = bal;
}
void deposit(double amount) {
balance += amount;
}
bool withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
return true;
}
return false;
}
void display() {
cout << "Account Number: " << accountNumber << endl;
cout << "Balance: " << balance << endl;
}
};
class SavingsAccount : public Account {
double interestRate;
public:
SavingsAccount(string acc, double bal, double rate) : Account(acc, bal) {
interestRate = rate;
}
double calculateInterest() {
return balance * interestRate / 100;
}
};
class CurrentAccount : public Account {
double overdraftLimit;
public:
CurrentAccount(string acc, double bal, double limit) : Account(acc, bal) {
overdraftLimit = limit;
}
bool canWithdraw(double amount) {
return amount <= balance + overdraftLimit;
}
};
int main() {
SavingsAccount s("S123", 1000, 5);
CurrentAccount c("C123", 500, 300);
[Link](500);
[Link](200);
[Link](600);
cout << "Savings Account Interest: " << [Link]() << endl;
cout << "Can Current Account Withdraw 800? " << ([Link](800) ? "true" : "false") << endl;
[Link]();
[Link]();
return 0;
}
Terminal Output:
$ g++ [Link] -o account
$ ./account
Savings Account Interest: 65
Can Current Account Withdraw 800? true
Account Number: S123
Balance: 1300
Account Number: C123
Balance: -100