Lesson 13 of 20Object-Oriented C++25 min

Constructors, Destructors, and Encapsulation

Constructors establish a valid starting state for an object. Destructors run when an object is destroyed. Encapsulation protects internal data by controlling how it can be accessed and changed.

Constructor and Private Data

Encapsulated BankAccount class
#include <iostream>
#include <string>
using namespace std;

class BankAccount
{
private:
    string accountName;
    double balance;

public:
    BankAccount(string name, double openingBalance)
        : accountName(name), balance(openingBalance)
    {
    }

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

    double getBalance() const
    {
        return balance;
    }
};

int main()
{
    BankAccount account("Alice", 500.0);
    account.deposit(150.0);
    cout << "Balance: " << account.getBalance() << endl;

    return 0;
}

Why Encapsulation Helps

Destructor

A destructor has the class name preceded by ~. You rarely need to write one when class members manage their own resources, but it is important to understand when it runs.

Destructor syntax
~BankAccount()
{
    // Cleanup code runs when the object is destroyed.
}
Practice task

Create an encapsulated Temperature class that rejects values below absolute zero.

Lesson Summary

Initialise objects correctly and protect class data with private members.