-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path8-virtual.cpp
More file actions
46 lines (36 loc) · 930 Bytes
/
8-virtual.cpp
File metadata and controls
46 lines (36 loc) · 930 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Subtype polymorphism: virtual functions and methods
#include <iostream>
#include <string>
#include <vector>
class Account {
public:
explicit Account(int balance) : balance(balance) {}
virtual ~Account() = default;
virtual std::string describe() const {
return "Balance: " + std::to_string(balance);
}
protected:
int balance;
};
class SavingsAccount : public Account {
public:
using Account::Account;
std::string describe() const override {
return "Savings -> " + Account::describe();
}
};
class CreditAccount : public Account {
public:
using Account::Account;
std::string describe() const override {
return "Credit -> " + Account::describe();
}
};
int main() {
std::vector<Account*> accounts;
accounts.push_back(new SavingsAccount(5000));
accounts.push_back(new CreditAccount(-750));
for (const auto& account : accounts) {
std::cout << account->describe() << '\n';
}
}