Constructors (Introduction)
A constructor is a special member function of a class that is automatically called when an object is created.
Main idea:
Constructor’s job is to initialize the object.
That means:
• Give initial values to variables
• Prepare the object to be used
Why Constructor is Needed (Purpose)
Without constructor:
Variables inside s may contain:
• Garbage values
• Undefined data
Constructor ensures:
• Object starts in a valid state
• Data is properly initialized
So the purpose of constructor is:
• Automatic initialization
• Safety
• Clean object creation
Special Properties of Constructor
A constructor has these rules:
• Same name as class
• No return type (not even void)
• Called automatically
• Runs only once per object
Example:
How Constructor Works (Memory Level)
When you write:
The system does this:
Allocates memory for object
s1Calls constructor automatically
Initializes variables
Object becomes ready
You never call constructor manually.
Example 1: Simple Constructor
Explanation:
• Constructor runs automatically
• roll gets value 1
• Object is ready before use
Types of Constructors (Conceptual)
Even without naming types deeply, constructors can:
• Take no parameters
• Take parameters
• Set default values
Constructor with Parameters
Purpose:
Initialize object using values provided by user.
Example:
Usage:
Each object:
• Has its own value
• Uses same constructor logic
Example 2: Parameterized Constructor
Explanation:
• Constructor sets data
• Objects are created fully initialized
Default Values Using Constructor
This ensures:
• No garbage value
• Safe object
Destructors (Introduction)
A destructor is a special member function that is automatically called when an object is destroyed.
Main idea:
Destructor’s job is to clean up resources.
Why Destructor is Needed (Purpose)
Destructor is used to:
• Free memory
• Release resources
• Close files
• Clean up before object dies
This prevents:
• Memory leaks
• Resource waste
Special Properties of Destructor
• Same name as class
• Starts with ~
• No return type
• No parameters
• Called automatically
Example:
When Destructor is Called
Destructor is called when:
• Object goes out of scope
• Function ends
• Program ends
• Object is deleted
Memory-Level Understanding
When object is destroyed:
Destructor executes
Cleanup code runs
Memory is freed
Order is guaranteed.
Example 3: Simple Destructor
Output order:
This proves:
• Constructor → object creation
• Destructor → object destruction
Constructor & Destructor Together (Very Important)
They always work as a pair.
Example:
For each object:
• Constructor runs once
• Destructor runs once
Example 4: Destructor with Dynamic Memory
Explanation:
• Constructor allocates memory
• Destructor frees memory
• Prevents memory leak
Object Destruction Order (Extra Important)
Objects are destroyed:
• In reverse order of creation
Example:
Destruction order:
• b destroyed first
• a destroyed last