AlgoDaily

OOP Basics: Classes and Objects

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Why Objects Now

From functions to modeled things

In Functions And Recursion, you learned to package behavior into reusable units. Classes take the next step: they let you package data and behavior together.

That matters because real programs usually talk about things:

  • A finance app has accounts, trades, and portfolios
  • A game has players, enemies, and items
  • An AI system has models, datasets, and predictions

In C++, a class describes what a kind of thing has and can do. An object is one actual thing created from that description.

Why Objects Now

Class Vs Object

Blueprint vs built thing

A class is a blueprint. It defines the shape of a type you create.

An object is an actual instance made from that blueprint.

Class: BankAccount
  - balance
  - deposit()
  - withdraw()

Objects:
  checkingAccount
  savingsAccount

Each object has its own data, even though all objects created from the same class share the same structure and available operations.

If you come from web development, this is similar to defining a component or model type, then creating actual component/model instances from it.

Class Vs Object

Define A Class

Your first custom type

A class definition usually contains:

  • Data members: variables owned by each object
  • Member functions: functions called on an object
  • An ending semicolon after the closing brace

Here we model a simple stock position. The object stores the ticker, number of shares, and price per share. Its member function calculates market value.

```cpp
#include <iostream>
#include <string>

class StockPosition {
public:
    std::string symbol;
    int shares;
    double pricePerShare;

    double marketValue() {
        return shares * pricePerShare;
    }
};

int main() {
    StockPosition position;
    position.symbol = "AAPL";
    position.shares = 10;
    position.pricePerShare = 175.25;

    std::cout << position.symbol << " value: $"
              << position.marketValue() << std::endl;

    return 0;
}
```

Object Access

You have an object named position with a member function named marketValue.

Which expression calls that member function on the object?

Public And Private

Objects should protect their own rules

So far, symbol, shares, and pricePerShare were public. That is convenient for learning, but real classes often hide data behind functions.

C++ uses access labels:

  • public: code outside the class can access it
  • private: only the class's own member functions can access it

This helps keep an object valid. For example, a bank account should not let random code set the balance to an impossible value without going through rules like deposit or withdraw.

```cpp
#include <iostream>

class BankAccount {
private:
    double balance;

public:
    BankAccount(double startingBalance) {
        balance = startingBalance;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }

    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account(100.0);
    account.deposit(25.0);
    account.withdraw(40.0);

    std::cout << "Balance: $" << account.getBalance() << std::endl;
    return 0;
}
```

Constructor Purpose

True or false:

A constructor is commonly used to initialize a new object when it is created.

Many Objects

Same class, separate state

A class can create many objects. Each object owns its own copy of the non-static data members.

That is the big shift from only using standalone variables and functions: instead of juggling separate arrays or loose variables, you can group the data and operations that belong together.

In the example below, two AI model evaluations are created from the same class, but they store different names and scores.

```cpp
#include <iostream>
#include <string>

class ModelScore {
private:
    std::string name;
    double accuracy;

public:
    ModelScore(std::string modelName, double modelAccuracy) {
        name = modelName;
        accuracy = modelAccuracy;
    }

    void printReport() {
        std::cout << name << " accuracy: " << accuracy << "%" << std::endl;
    }
};

int main() {
    ModelScore baseline("Baseline", 82.5);
    ModelScore improved("Improved", 89.7);

    baseline.printReport();
    improved.printReport();

    return 0;
}
```

Instance Name

A specific instance created from a class is called an _____.

Designing Small Classes

A practical class checklist

When deciding whether to make a class, ask:

  1. What thing am I modeling?

    • Example: BankAccount, Trade, UserProfile, ModelScore
  2. What data belongs to each instance?

    • Example: balance, ticker symbol, username, accuracy
  3. What actions should that thing perform?

    • Example: deposit money, calculate value, print a report
  4. Which details should be protected?

    • Keep internal state private when outside code should not freely change it

A good beginner class is usually small, named clearly, and responsible for one idea.

Designing Small Classes

What Changed

Which statement best captures the main purpose of a class in basic C++ object-oriented programming?

OOP Foundation

You can now model programs with objects

You have learned the core OOP basics:

  • A class defines a custom type
  • An object is an instance of that class
  • Data members store object state
  • Member functions define object behavior
  • public and private control what outside code can access
  • Constructors help initialize objects

This gives you a cleaner way to organize programs as they grow beyond simple functions. Next, we will build on this foundation with more advanced object-oriented ideas like inheritance and polymorphism.

OOP Foundation

Open interactive view →