Topic 9

Constructors and Destructors

3 min read3 questions to test yourself

1Definition

A Constructor is a special member function of a class that is invoked automatically whenever an object of that class is instantiated. It initializes object data members. A Destructor is a special member function that is executed automatically when an object goes out of scope or is destroyed, releasing allocated resources.

2Simple Explanation

  • Constructor: The Birth Certificate & Initial Setup of an object. When a new house is built, the contractor installs plumbing and paints the walls (initializes attributes).
  • Destructor: The Demolition Crew. When a building is designated for removal, the demolition crew safely disconnects electrical lines and frees up the physical lot space (releases memory).

3Real-Life Example / Analogy

  • When you open a new tab in a web browser (Object Creation), a Constructor allocates memory and loads default home settings.
  • When you close the tab (Object Destruction), a Destructor clears temporary caches and frees memory back to the operating system.

4Diagram / Visual Representation

Object declaration / creation

Constructor runs

Object in active use

Scope ends or delete is called

Destructor runs: ~ClassName()

5Working / How It Works

  • Constructor Naming: Must match the exact name of the class. Has no return type (not even void).
  • Destructor Naming: Matches class name, prefixed with a tilde symbol (~ClassName()). Takes no parameters and cannot be overloaded.

6Types / Components / Characteristics

  • Types of Constructors:
    1. Default Constructor: Takes no parameters.
    2. Parameterized Constructor: Accepts parameters to initialize attributes with custom values.
    3. Copy Constructor: Initializes an object using another existing object of the same class (ClassName(const ClassName &obj)).

7Solved Examples / Problems

Problem Statement: Demonstrate Default, Parameterized, and Copy Constructors alongside a Destructor in C++.

C++
#include <iostream>
using namespace std;
class Sample {
public:
    int value;
    // Default Constructor
    Sample() {
        value = 0;
        cout << "Default Constructor" << endl;
    }
    // Parameterized Constructor
    Sample(int v) {
        value = v;
        cout << "Parameterized Constructor: " << value << endl;
    }
    // Copy Constructor
    Sample(const Sample &s) {
        value = s.value;
        cout << "Copy Constructor: " << value << endl;
    }
    // Destructor
    ~Sample() {
        cout << "Destructor Executed for value: " << value << endl;
    }
};
int main() {
    Sample obj1;        // Default
    Sample obj2(100);   // Parameterized
    Sample obj3(obj2);  // Copy Constructor
    return 0;
}

Output:

Output
Default Constructor
Parameterized Constructor: 100
Copy Constructor: 100
Destructor Executed for value: 100
Destructor Executed for value: 100
Destructor Executed for value: 0

8Advantages, Disadvantages & Applications

  • Advantages:
    • Prevents garbage values by guaranteeing immediate initialization.
    • Automatic memory cleanup prevents leaks (RAII pattern).
  • Disadvantages:
    • Shallow copy in default copy constructors can lead to double-free crashes on heap pointers.
  • Applications: File handle management, database connection wrappers.

9Important Points to Remember

  • If no constructor is defined by the developer, the compiler automatically supplies a default constructor.
  • Destructors for stack objects run in exact reverse order of their creation.

10Test Your Understanding

  1. Conceptual Question: What is the difference between a Shallow Copy and a Deep Copy in a Copy Constructor?
    Show answer
    A Shallow copy duplicates pointer addresses (pointing to identical memory), whereas a Deep copy allocates new memory and copies the actual underlying data values.
  2. MCQ: What symbol precedes a Destructor declaration in C++?
    • A) *
    • B) &
    • C) ~
    • D) #
    Show answer
    C) ~
  3. Application Question: How many times is the Destructor called for Sample arr[5];?
    Show answer
    5 times, once for each object in the array.

Finished this topic?

0 of 14 topics read in Object-Oriented Programming

Handwritten notes for the exam

Unit-wise SPPU notes and PYQs for this subject.

Helpful? Share it with your class

Free for everyone, no login needed.

Share topic