BIT153 Object Oriented Programming

Object Oriented ProgrammingUnit 37 min read

Constructors & Destructors: Object Initialization & Cleanup

Unit 3 of Object Oriented Programming: Explores how constructors initialize objects, destructors release resources, and how these mechanisms work in inheritance hierarchies—with code examples, step-by-step traces, and real-world parallels like app startup and memory cleanup.

1. Why Constructors and Destructors?

Objects need initialization (setup) and cleanup (resource release). Constructors handle initialization; destructors handle cleanup.

Key Roles

  • Constructor: Called when an object is created. Sets initial state.
  • Destructor: Called when an object is destroyed. Releases resources (e.g., memory, file handles).

2. Types of Constructors

Constructors can be categorized based on their behavior and purpose.

2.1 Default Constructor

  • No arguments.
  • Automatically called if no other constructor is defined.
  • Initializes members to default values (e.g., 0 for integers, nullptr for pointers).
flowchart TD
    A["Object Creation"] --> B["Default Constructor Called"]
    B --> C["Members Initialized to Default"]

2.2 Parameterized Constructor

  • Takes arguments to initialize members.
  • Ensures objects start in a valid state.
flowchart TD
    A["Object Creation"] --> B["Parameterized Constructor Called"]
    B --> C["Members Initialized with Provided Values"]

2.3 Copy Constructor

  • Creates a new object as a copy of an existing one.
  • Critical for deep copying (avoids shallow copy pitfalls).
flowchart TD
    A["Object A"] --> B["Copy Constructor Called"]
    B --> C["Object B Copied from A"]

2.4 Constructor Overloading

  • Multiple constructors with different parameters.
  • Allows flexible initialization.
flowchart TD
    A["Object Creation"] --> B["Constructor Overloading"]
    B --> C["Choose Constructor Based on Arguments"]

3. Constructor Initialization List

For efficient initialization, use the initialization list (not assignment).

class Time {
    int hours, minutes, seconds;
public:
    Time(int h, int m, int s) : hours(h), minutes(m), seconds(s) {} // Initialization list
};

Why?

  • Faster than assignment.
  • Ensures members are initialized before the constructor body runs.

4. Destructors

  • Called when an object goes out of scope or is explicitly deleted.
  • Used to release resources (e.g., free memory, close files).
class ResourceHolder {
    int* data;
public:
    ~ResourceHolder() { delete[] data; } // Destructor
};

Key Points

  • No return type or parameters.
  • Called automatically for each object.

5. Constructor and Destructor Chains in Inheritance

When a derived class inherits from a base class, constructors/destructors are called in a specific order.

Order of Execution

  1. Base class constructor → Derived class constructor → Member objects’ constructors.
  2. Derived class destructor → Base class destructor → Member objects’ destructors.
flowchart TD
    A["Base Class Constructor"] --> B["Derived Class Constructor"]
    B --> C["Member Objects' Constructors"]
    C --> D["Derived Class Destructor"]
    D --> E["Base Class Destructor"]

6. Worked Example: Time Class

Problem: Create a Time class with constructors to initialize hours, minutes, and seconds.

#include <iostream>
using namespace std;

class Time {
    int hours, minutes, seconds;
public:
    // Default constructor
    Time() : hours(0), minutes(0), seconds(0) {}

    // Parameterized constructor
    Time(int h, int m, int s) : hours(h), minutes(m), seconds(s) {}

    // Display time
    void display() {
        cout << hours << ":" << minutes << ":" << seconds << endl;
    }
};

int main() {
    Time t1;               // Default constructor
    Time t2(12, 30, 45);   // Parameterized constructor
    t1.display();          // Output: 0:0:0
    t2.display();          // Output: 12:30:45
    return 0;
}

Trace Table

Object Constructor Called State After Initialization
t1 Default hours=0, minutes=0, seconds=0
t2 Parameterized hours=12, minutes=30, seconds=45

7. Comparison Table: Constructors vs. Destructors

Feature Constructor Destructor
Purpose Initialize objects Clean up resources
Return Type None None
Parameters Can have arguments No parameters
Overloading Supported Not supported
Order in Inheritance Base → Derived → Members Derived → Base → Members

8. Real-World Applications

In the Real World

  1. eSewa App (Nepal)

    • Idea: Constructors initialize user sessions and transaction states.
    • How: When a user logs in, an Account object is created with their balance (initialized via constructor). The destructor ensures the session is closed properly.
  2. Google Maps (Worldwide)

    • Idea: Destructors release GPS location data.
    • How: When a user closes the app, destructors clean up temporary maps and location caches to save memory.
  3. Ncell (Nepal)

    • Idea: Constructors initialize SIM card data.
    • How: When a new SIM is activated, a SIM object is created with default settings (e.g., dataUsage=0). The destructor ensures data is saved before the SIM is deactivated.

9. Common Pitfalls and Best Practices

  • Avoid shallow copying: Always define a copy constructor if deep copying is needed.
  • Initialize members in the constructor: Use the initialization list for efficiency.
  • Release resources in the destructor: Prevent memory leaks.
  • Avoid recursive constructor calls: Can lead to stack overflow.

10. Exam Tip

  • Focus on:
    • Constructor types (default, parameterized, copy).
    • Constructor initialization list (why it’s better than assignment).
    • Order of constructor/destructor calls in inheritance.
    • Practical examples (e.g., Time class, resource cleanup).
  • Common questions:
    • Differentiate between constructors and destructors.
    • Explain the chain of constructor/destructor calls in inheritance.
    • Write a program demonstrating constructor overloading.
  • Marking scheme:
    • 20%: Definition and types of constructors.
    • 30%: Code implementation (correct syntax, initialization list).
    • 25%: Inheritance chain explanation.
    • 25%: Practical example (e.g., Time class with trace).

11. Practice Problems

  1. Write a BankAccount class with:
    • A default constructor (balance = 0).
    • A parameterized constructor (balance = initial deposit).
    • A destructor to print "Account closed."
  2. Explain why the following code causes a memory leak:
    class DynamicArray {
        int* arr;
    public:
        DynamicArray(int size) { arr = new int[size]; }
        ~DynamicArray() {} // Missing cleanup!
    };
    
  3. Create a Student class with a copy constructor to deep copy grades.

12. Summary

  • Constructors initialize objects; destructors clean them up.
  • Types: default, parameterized, copy, and overloaded.
  • Initialization list is efficient.
  • Inheritance follows a strict order: base → derived → members.
  • Real-world apps (eSewa, Google Maps) rely on these mechanisms.

Based on the TU BIT syllabus for Object Oriented Programming (BIT153), unit 3.

Discussion

Loading…