Object-Oriented Programming in C++
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
From Functions To Objects
Why this lesson matters
In Introduction to C++, you wrote programs with variables, decisions, loops, and functions. That is enough for small programs.
But real software quickly needs a way to keep related data and behavior together.
Object-oriented programming, or OOP, gives you that structure. In C++, OOP helps you model concepts like:
- A user account with a username and login behavior
- A trading position with a ticker, quantity, and market value
- An AI model configuration with parameters and validation
- A game character with health and actions
The main idea: instead of passing loose variables around everywhere, you create objects that represent meaningful things in your program.

Classes And Objects
The core OOP vocabulary
A class is a blueprint. It describes what data an object has and what it can do.
An object is a real instance created from that blueprint.
Think of a class like a reusable component definition in web development. The class says what fields and behavior exist; each object has its own actual values.
In C++, a class can contain:
- Data members: variables stored inside each object
- Member functions: functions that belong to the class
Here is a small finance-flavored example.
```cpp
#include <iostream>
#include <string>
using namespace std;
class StockPosition {
public:
string ticker;
int shares;
double price;
double marketValue() {
return shares * price;
}
};
int main() {
StockPosition position;
position.ticker = "AAPL";
position.shares = 10;
position.price = 175.50;
cout << position.ticker << " position value: $"
<< position.marketValue() << endl;
return 0;
}
```
Blueprint Or Instance
In C++ OOP, which statement best describes the difference between a class and an object?
Encapsulation Protects State
Public vs. private
One of the most important OOP ideas is encapsulation: hide internal details and expose a safer interface.
In C++, class members are usually controlled with access specifiers:
-
public: accessible from outside the object -
private: accessible only inside the class
Why does this matter?
Imagine a bank account, trading account, or credit balance. You probably do not want random code setting the balance to any value. Instead, you expose controlled actions like deposit() or withdraw().
This keeps your object in a valid state.
```cpp
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
public:
BankAccount() {
balance = 0.0;
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount account;
account.deposit(250.00);
if (account.withdraw(80.00)) {
cout << "Withdrawal approved." << endl;
}
cout << "Current balance: $" << account.getBalance() << endl;
return 0;
}
```
Hide The Details
Fill in the blank:
The C++ access specifier commonly used to hide class data from outside code is ____.
Constructors Create Objects
Objects need good starting values
A constructor is a special member function that runs when an object is created.
Constructors are useful because they let you initialize an object immediately, instead of creating an object first and filling in its fields later.
In C++, constructors:
- Have the same name as the class
- Do not have a return type
- Can receive parameters
- Often use an initializer list to set member values
This is especially useful when an object should never exist in a half-valid state.
```cpp
#include <iostream>
#include <string>
using namespace std;
class ModelConfig {
private:
string modelName;
double learningRate;
public:
ModelConfig(string name, double rate)
: modelName(name), learningRate(rate) {
}
void printSummary() {
cout << "Model: " << modelName << endl;
cout << "Learning rate: " << learningRate << endl;
}
};
int main() {
ModelConfig config("FraudDetector", 0.01);
config.printSummary();
return 0;
}
```
Constructor Check
True or false:
A constructor in C++ must have the same name as the class.
Inheritance Basics
Reusing behavior with inheritance
Inheritance lets one class build on another class.
A derived class can reuse behavior from a base class and add more specific behavior of its own.
For example:
Account
├── CheckingAccount
└── SavingsAccount
CheckingAccount and SavingsAccount are both kinds of Account, but each may have extra rules.
Use inheritance when there is a true is-a relationship:
- A
SavingsAccountis anAccount - A
Manageris anEmployee - A
NeuralNetworkModelis aModel
Do not use inheritance just to share random code. If one object simply owns another object, that is usually a has-a relationship instead.

Is-A Or Has-A
Which relationship is the best candidate for inheritance?
Designing Cpp Classes
A practical class-design checklist
When you design a C++ class, ask:
What concept does this represent?
Example:BankAccount,User,ModelConfig,TradeOrder.What data belongs inside it?
These become data members.What actions should it expose?
These become public member functions.What should outside code not touch directly?
These should usually be private.How should the object be created safely?
This is where constructors help.
OOP is not about adding classes everywhere. It is about creating clean boundaries so your program stays understandable as it grows.
Next, in Data Structures in C++, you will see how C++ organizes collections of values and objects.
