Mark As Completed Discussion

In the previous section, we created a BankAccount class with properties like account_owner and balance, and methods like deposit() and withdraw(). Now, let's see how we can create or instantiate objects of this class in C++. Objects are instances of a class, meaning they hold their own set of properties.

In C++, objects can be created by simply declaring them in the following format: ClassName objectName(parameters);.

Consider this C++ code:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5// Instantiating our BankAccount class
6BankAccount account1("James", 5000.0);
7BankAccount account2("Sophia", 3000.0);
8
9// Displaying initial account balances
10std::cout << "James's initial balance: " << account1.balance << std::endl;
11std::cout << "Sophia's initial balance: " << account2.balance << std::endl;
12
13// Using the deposit method
14account1.deposit(2000);
15account2.deposit(1000);
16
17// Displaying updated account balances
18std::cout << "James's updated balance: " << account1.balance << std::endl;
19std::cout << "Sophia's updated balance: " << account2.balance << std::endl;
20
21return 0;
22}

Here, we're creating two objects of the BankAccount class - account1 for James and account2 for Sophia. Initial balances for both accounts are set during object creation using the constructor method. Then, we're using the deposit() method on both account objects to deposit some amount in their respective accounts.

In summary, creating an object in C++ involves instantiating a class, and then using the object to access the properties and methods offered by the class. This is a strong beginner step in building complex systems, for instance, a banking software that manages accounts and transactions. Remember, every time we create an object (like account1 and account2), it carries its own set of properties (i.e., a separate set of account_owner and balance values).

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment