In C++ programming, classes are defined using the class
keyword, followed by the name of the class and a pair of curly braces {}
which enclose the class's data members and member functions. Let's see how we can define a class in the context of a bank, as it aligns with our goals to understand finance.
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4class BankAccount {
5public:
6string account_owner;
7double balance;
8
9// Class Constructor
10BankAccount(string owner, double initial_balance) {
11account_owner = owner;
12balance = initial_balance;
13}
14
15// A member function for depositing money
16void deposit(double amount) {
17balance += amount;
18}
19
20// A member function for withdrawing money
21void withdraw(double amount) {
22if (balance > amount)
23balance -= amount;
24else
25std::cout << "Insufficient balance!" << std::endl;
26}
27};
28
29int main() {
30BankAccount my_account("Josh", 1000.0);
31my_account.deposit(500);
32my_account.withdraw(200);
33}
Here, BankAccount
is the name of our class. It has two data members account_owner
and balance
, and three member functions that are BankAccount()
, deposit()
, and withdraw()
.
The constructor function has the name of the class and is used to initialize the object. It is automatically called when an object of the class is created.
Lastly, functions deposit()
and withdraw()
are used to deposit money and withdraw money from the account respectively.
xxxxxxxxxx
33
}
using namespace std;
class BankAccount {
public:
string account_owner;
double balance;
// Class Constructor
BankAccount(string owner, double initial_balance) {
account_owner = owner;
balance = initial_balance;
}
// A member function for depositing money
void deposit(double amount) {
balance += amount;
}
// A member function for withdrawing money
void withdraw(double amount) {
if (balance > amount)
balance -= amount;
else
std::cout << "Insufficient balance!" << std::endl;
}
};
int main() {
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment