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
- Prevents invalid direct changes to important data.
- Keeps validation inside the class.
- Makes the public interface easier to understand.
- Allows the internal implementation to change later.
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.