Function overriding is a powerful mechanism in object-oriented C++ that allows derived classes to redefine inherited functions from base classes.
Example: Overriding deposit
Function in Banking Accounts
Let’s illustrate function overriding with a banking account scenario:
class BankAccount {
public:
virtual void deposit(double amount) {
// Base class implementation (common logic for all accounts)
balance += amount;
}
protected:
double balance = 0.0;
};
class SavingAccount : public BankAccount {
public:
void deposit(double amount) override {
// Derived class implementation (specific to savings accounts)
balance += amount + (amount * interestRate);
}
private:
double interestRate = 0.01; // Example interest rate
};
int main() {
SavingAccount mySavings;
mySavings.deposit(100.0); // Calls SavingAccount's deposit with interest
BankAccount genericAccount; // Base class object
genericAccount.deposit(100.0); // Calls BankAccount's deposit (no interest)
}
BankAccount
class serves as the base class with a deposit
function that performs the common task of adding the amount to the balance. It’s declared as virtual
to allow overriding in derived classes.SavingAccount
class inherits from BankAccount
. It overrides the deposit
function, providing its own implementation that adds the interest rate to the deposited amount.main
function depends on the object’s type at runtime (runtime polymorphism). When you call deposit
on a SavingAccount
object, the overridden version with interest calculation is executed.Assignment Title: “E-Commerce Discount System”
Objective:
Develop a C++ program simulating an e-commerce discount system where various types of users receive different discount rates on their purchases. The assignment will help practice inheritance, function overriding, and virtual functions.
Requirements:
User
name
(string), userID
(int)getDiscount()
, which returns a default discount rate (e.g., 0%).GuestUser
(inherits User
)
getDiscount()
to apply a low discount rate (e.g., 5%).RegisteredUser
(inherits User
)
purchaseAmount
(double)getDiscount()
to apply a higher discount based on purchaseAmount
(e.g., 10% if purchaseAmount > 100).PremiumUser
(inherits RegisteredUser
)
getDiscount()
to provide the highest discount rate (e.g., 20%).GuestUser
, RegisteredUser
, and PremiumUser
).User
to call the getDiscount()
function and display the appropriate discount for each type.