Aral Code

Object-Oriented Programming Lesson 13 of 17

C++ Constructors, Destructors and Encapsulation

Initialize objects with constructors and member initializer lists, overload constructors, clean up with destructors, use getters and setters, and add static members.

Setting each member one by one after creating an object is tedious and error-prone. A constructor sets up an object correctly from the moment it's created, and a destructor cleans up when it's destroyed.

Constructors

#include <iostream>
#include <string>
using namespace std;

class Student {
private:
    string name;
    int gradeLevel;
public:
    Student(string n, int g) : name(n), gradeLevel(g) {}   // constructor

    void introduce() const {
        cout << "Hi, I'm " << name << " from Grade " << gradeLevel << "." << endl;
    }
};

int main() {
    Student a("Gabriela", 11);
    Student b{"Andres", 12};
    a.introduce();
    b.introduce();
    return 0;
}

Output

Hi, I'm Gabriela from Grade 11.
Hi, I'm Andres from Grade 12.
  • A constructor has the same name as the class and no return type.
  • : name(n), gradeLevel(g) is a member initializer list. It initializes members directly and is the preferred style.
  • Both Student a("Gabriela", 11); and Student b{"Andres", 12}; call the constructor.

Overloaded and default constructors

#include <iostream>
#include <string>
using namespace std;

class Product {
    string name;
    double price;
    int stock;
public:
    Product() : Product("Unnamed", 0, 0) {}                          // default
    Product(string n, double p, int s = 0) : name(n), price(p), stock(s) {}

    void show() const { cout << name << " P" << price << " x" << stock << endl; }
};

int main() {
    Product a;
    Product b("Bigas", 52, 80);
    Product c("Asukal", 70);
    a.show();
    b.show();
    c.show();
    return 0;
}

Output

Unnamed P0 x0
Bigas P52 x80
Asukal P70 x0

The default constructor delegates to the other one. If you write any constructor yourself, the compiler no longer creates a default one, so Product a; only works if you provide it.

Encapsulation with getters and validated setters

#include <iostream>
#include <string>
using namespace std;

class BankAccount {
    string owner;
    double balance = 0;
public:
    BankAccount(string o, double initial) : owner(o) { deposit(initial); }

    const string &getOwner() const { return owner; }
    double getBalance() const { return balance; }

    bool deposit(double amount) {
        if (amount <= 0) return false;
        balance += amount;
        return true;
    }
    bool withdraw(double amount) {
        if (amount <= 0 || amount > balance) return false;
        balance -= amount;
        return true;
    }
};

int main() {
    BankAccount acct("Juan", 1000);
    acct.deposit(500);
    if (!acct.withdraw(5000)) cout << "Withdrawal denied." << endl;
    acct.withdraw(300);
    cout << acct.getOwner() << ": P" << acct.getBalance() << endl;
    return 0;
}

Output

Withdrawal denied.
Juan: P1200

balance can only change through deposit and withdraw, which refuse invalid amounts. The object protects its own data.

Destructors

A destructor runs automatically when an object is destroyed, for example when it goes out of scope. Its name is ~ plus the class name:

#include <iostream>
#include <string>
using namespace std;

class Logger {
    string task;
public:
    Logger(string t) : task(t) { cout << "Start: " << task << endl; }
    ~Logger() { cout << "End: " << task << endl; }
};

int main() {
    Logger a("Quarterly report");
    {
        Logger b("Checking grades");
        cout << "...working..." << endl;
    }   // b is destroyed here
    cout << "Back in main" << endl;
    return 0;
}   // a is destroyed here

Output

Start: Quarterly report
Start: Checking grades
...working...
End: Checking grades
Back in main
End: Quarterly report

Destructors are used to release resources: closing files, freeing memory, disconnecting from a database. This "automatic cleanup when leaving scope" idea (called RAII) is one of C++'s most important strengths.

Static members

#include <iostream>
using namespace std;

class Ticket {
    static int nextNumber;    // shared by all tickets
    int number;
public:
    Ticket() : number(nextNumber++) {}
    int get() const { return number; }
    static int issued() { return nextNumber - 1; }
};
int Ticket::nextNumber = 1;   // define the static member once

int main() {
    Ticket a, b, c;
    cout << a.get() << " " << b.get() << " " << c.get() << endl;
    cout << "Issued: " << Ticket::issued() << endl;
    return 0;
}

Output

1 2 3
Issued: 3

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. What is the name of the destructor for class Product?
2. What does : name(n), price(p) after a constructor do?
3. When does a local object's destructor run?
4. If you write Product(string n) only, does Product p; still compile?

By Sir Reyel · Last updated 2026-12-04