In the Object-Oriented Programming (OOP) paradigm, objects and classes are the primary building blocks. They help us model and solve real-world problems efficiently.
Class
In C++, a class is a blueprint for creating objects. It can be compared to a factory's mould that gives shape to its products. For example, consider a class BankAccount
. All bank accounts, regardless of who owns them, have some common characteristics such as an account number, balance, and operations like deposit, withdrawal, and balance inquiry. A class encapsulates these common properties and behaviors.
Object
On the other hand, an object is an instance of a class. Going by our banking analogy, each customer's account is an object of the class BankAccount
. Each object has access to all the properties and behaviors defined in the class, but its state (its variables' values) is independent of other objects. For instance, two BankAccount objects will have different account numbers and balances.
Understanding this Class-Object relationship is essential for writing efficient, modular, and bug-resistant OOP code. Below is a simple example of a class and its objects in C++.
xxxxxxxxxx
}
using namespace std;
// Define a simple BankAccount class
class BankAccount {
public:
string account_number;
double balance = 0.0;
void deposit(double amount) {
balance += amount;
cout << amount << " deposited. Current balance: " << balance << endl;
}
void withdraw(double amount) {
if (balance - amount >= 0) {
balance -= amount;
cout << amount << " withdrawn. Current balance: " << balance << endl;
} else {
cout << "Insufficient balance." << endl;
}
}
};
int main() {
// Use the BankAccount class to create two bank account objects
BankAccount johnsAccount;
BankAccount amysAccount;
Build your intuition. Is this statement true or false?
In C++, objects can't access all the properties and behaviors defined in the class they are an instance of.
Press true if you believe the statement is correct, or false otherwise.
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.
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
}
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() {
Let's test your knowledge. Fill in the missing part by typing it in.
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. For example, let's define a class in the context of a bank. BankAccount
is the name of our class. Now, can you remember what is the purpose of the BankAccount()
function within the class? It is used to _ the object and is automatically called when an object of the class is created.
Write the missing line below.
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:
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).
xxxxxxxxxx
using namespace std;
int main() {
// Instantiating our BankAccount class
BankAccount account1("James", 5000.0);
BankAccount account2("Sophia", 3000.0);
// Displaying initial account balances
std::cout << "James's initial balance: " << account1.balance << std::endl;
std::cout << "Sophia's initial balance: " << account2.balance << std::endl;
// Using the deposit method
account1.deposit(2000);
account2.deposit(1000);
// Displaying updated account balances
std::cout << "James's updated balance: " << account1.balance << std::endl;
std::cout << "Sophia's updated balance: " << account2.balance << std::endl;
return 0;
}
Build your intuition. Is this statement true or false?
In C++, objects can only be created by using the 'new' keyword.
Press true if you believe the statement is correct, or false otherwise.
After defining a class and creating instances (or objects) of the class, the next step is using these objects.
Objects are used mainly to interact with the methods and properties defined within the class. The syntax to access methods of an object in C++ is: objectName.methodName(parameters);
Let's take up an example where we have created two objects of a hypothetical BankAccount
class - account1
for James and account2
for Sophia. Suppose we want to use these objects to interact with the withdraw()
and getBalance()
methods of our BankAccount
class.
1// Considering an object 'account1' of 'BankAccount' class
2account1.withdraw(1000);
3std::cout << "James's balance after withdrawal: " << account1.getBalance() << std::endl;
4
5// linking two objects
6account1.transfer(account2, 1000);
7std::cout << "Sophia's balance after transfer from James: " << account2.getBalance() << std::endl;
In this example, James withdraws an amount of 1000 from his account through the withdraw()
method accessed via his account object account1
. Then, we display his balance after withdrawal using the getBalance()
method. Similarly, we demonstrate a transfer()
method that transfers an amount from James' account to Sophia's account. After this transfer, we display Sophia's updated balance. Objects enable us to carry out such complex operations in a very intuitive and flexible manner.
In conclusion, objects are the cornerstone of OOP, they allow us to encapsulate related data and functions within a single class and perform various actions using this encapsulation. A senior engineer would likely appreciate the modularity and structure provided by objects in a system, which can greatly enhance the robustness, maintainability, and code-readability of programming projects.
xxxxxxxxxx
using namespace std;
int main() {
// Considering an object 'account1' of 'BankAccount' class
account1.withdraw(1000);
std::cout << "James's balance after withdrawal: " << account1.getBalance() << std::endl;
// linking two objects
account1.transfer(account2, 1000);
std::cout << "Sophia's balance after transfer from James: " << account2.getBalance() << std::endl;
return 0;
}
Are you sure you're getting this? Fill in the missing part by typing it in.
In C++, to access methods of an object we use the syntax: objectName.___(parameters);
. Fill in the blank.
Write the missing line below.
Putting It Together
Let's put together everything we've learned and look at an application of Object-Oriented Programming concepts.
Consider a scenario in finance. Suppose we're building a trading platform and we need a way to represent a trader who would have characteristics like a name and portfolio value. Here, we can consider each trader as an object
and hence can create a class
called Trader
.
We define the Trader
class with two private attributes, name
and portfolio_value
. The public section of the class contains a constructor that initializes these attributes and a showPortfolio()
method that, when called, outputs the name of the trader and their current portfolio value.
We can then create individual instances for different traders with their specific details. Such as 'Carl' having a portfolio value of $15000.00 and 'Jane' having $9800.50. We can do this using the syntax Trader ObjectName(Parameters)
as we've learned in the previous sections.
We can then use these objects to call the showPortfolio()
method and display the details. This helps us encapsulate the data and operations related to each trader within its own object. As the program grows and more traders are added, handling them becomes easier as they are separate objects.
In conclusion, classes and objects are powerful tools in C++ that allow for clear, organized, and efficient code. They encapsulate related data and functions into individual entities that can interact with each other in complex ways.
With classes and objects, we can build intricate systems, like a trading platform with numerous traders, that are organized and manageable. In each use case, they provide robustness, maintainability, and improved code-readability.
xxxxxxxxxx
}
using namespace std;
// Defining a class 'Trader'
class Trader {
private:
string name;
float portfolio_value;
public:
Trader(string n, float p_v) {
name = n;
portfolio_value = p_v;
}
void showPortfolio()
{
cout<<"Trader: "<<name<<"\nPortfolio value: $"<<portfolio_value<<endl;
}
};
int main() {
/* Creating objects and showcasing usage */
Trader t1("Carl", 15000.00);
Trader t2("Jane", 9800.50);
t1.showPortfolio();
t2.showPortfolio();
return 0;
Are you sure you're getting this? Is this statement true or false?
In C++, individual instances of a class can only be created using the syntax ClassName ObjectName;
.
Press true if you believe the statement is correct, or false otherwise.
Generating complete for this lesson!