C++ Classes and Objects

What a class is, how to define member variables and methods, and when to use public and private access.

To simplify development compared with purely procedural programming, C++ supports the object-oriented programming paradigm, including classes. Classes let programmers combine data and related functions in one structure, which often makes programs easier to organize and maintain.

Classes can be used to represent real-world objects. They may contain properties, which describe the characteristics or state of an object, and methods, which define the actions the object can perform.

For example, a BankAccount class can represent a bank account. It may contain a property such as balance, which stores the current amount of money in the account, and methods such as Deposit(), Withdraw(), and ShowBalance(), which define the actions that can be performed on that account.

#include <iostream>

class BankAccount
{
private:
    double balance_;

public:
    void Deposit(double amount)
    {
        balance_ = balance_ + amount;
    }

    void Withdraw(double amount)
    {
        if (amount <= balance_)
        {
            balance_ = balance_ - amount;
        }
        else
        {
            std::cout << "Not enough money in the account.\n";
        }
    }

    void ShowBalance()
    {
        std::cout << "Balance: " << balance_ << "\n";
    }
};

int main()
{
    BankAccount account;

    account.Deposit(1000.0);
    account.ShowBalance();

    account.Deposit(500.0);
    account.ShowBalance();

    account.Withdraw(300.0);
    account.ShowBalance();

    account.Withdraw(1500.0);

    return 0;
}
The underscore suffix on balance_ is a common naming convention used to show that this variable is a class member. It helps distinguish member variables from local variables or method parameters. C++ does not require this naming style, but many programmers use it to make code clearer.