Constructors in C++: Default & Parameterized Constructors
Overview: A default constructor can create an empty account.
What is a Constructor?
- In standard C or basic classes, when you create an object, its variables contain random garbage values until you manually call an input…
- Object Created Student s1; statement runs in main()
- Constructor Runs Student() sets rollNo = 0, marks = 0.0
- Initialized Object Zero garbage values!
View diagram · How a Constructor Executes Automatically
Key Characteristics of Constructors (Golden Exam Points)
- The six rules below are useful for practice.
- Same Name: It has the exact same name as the class.
- No Return Type: It has no return type at all, not even
void! - Placed in Public: It is almost always placed in the
public:section so objects can be created freely frommain(). - Runs Automatically: It executes automatically when an object is declared; you do not call it with a dot operator (
.). - Cannot be Inherited: A child class does not inherit the parent class constructor (though it can call it).
- Cannot be Virtual: Constructors cannot be marked as
virtual.
Types of Constructors: Default vs. Parameterized
- A. Default Constructor (Takes No Arguments): A constructor that takes no parameters is called a Default Constructor.
- Warning: When creating an object with a default constructor, write
Point p1;. - B. Parameterized Constructor (Takes Arguments): What if you want different students to have different roll numbers and marks right at the time of creation?
Comparison: Default vs. Parameterized Constructor
- Number of Arguments: Takes 0 arguments
- Values Assigned: Assigns fixed starting values (like 0 or empty) to all objects
- How to Call?:
Student s1;(No parentheses!) - Auto-generation: If you write NO constructor, compiler provides one automatically
Multiple Constructors & Default Argument Constructors in C++
Overview: If a class has both a no-argument constructor and a constructor whose every parameter has a default, constructing it with no arguments may be ambiguous.
Multiple Constructors (Constructor Overloading)
- In C++, you don’t have to stop at just one constructor.
- Complex c1; Calls Complex() (0 arguments) Sets real = 0, imag = 0
- Complex c2(5.5); Calls Complex(float) (1 argument) Sets real = 5.5, imag = 5.5
- Complex c3(4.0, 9.2); Calls Complex(float, float) (2 arguments) Sets real = 4.0, imag = 9.2
View diagram · Constructor Overloading Resolution
Constructors with Default Arguments
- Just like normal functions, you can also assign default values to constructor arguments.
The Dangerous Ambiguity Error (Exam Favorite!)
- Look at this tricky situation that often trips students up in exams:
- Why does this error happen?: When you write
Sample s1;, the compiler gets totally confused: - It could call
Sample()because 0 arguments were passed. - It could also call
Sample(int x = 0)by applying the default value0! - Exam Tip: Never write a 0-argument default constructor in the same class where another constructor has default values for all its…
Dynamic Initialization of Objects in C++: Concept & Examples
Overview: A constructor can receive a value read at runtime, such as the number of seats in a lab.
What is Dynamic Initialization of Objects?
- In simple programs, we often hardcode fixed numbers directly into the constructor (for example:
Point p(10, 20);).
View diagram · Compile-Time vs. Dynamic Runtime Initialization
Practical Case Study: Bank Fixed Deposit Calculator
- A classic example asked in university exams is the Bank Fixed Deposit Calculator.
- One customer enters rate as a decimal fraction (e.g.,
0.07for 7%). - Another customer enters rate as an integer percentage (e.g.,
7for 7%).
Key Advantages of Dynamic Initialization
- User Flexibility: The program does not force fixed numbers; it adapts to whatever data the user enters.
- Instant Calculations: Complex formulas (like compound interest) execute automatically inside the constructor the moment the object is created.
- Guarantees Valid Data: The object is fully calculated and ready to use immediately; zero chance of garbage values.
Copy Constructor & Dynamic Constructors in C++: Deep vs. Shallow Copy
Overview: If a class owns a dynamically allocated buffer, copying only its address makes two objects point at the same allocation.
What is a Copy Constructor?
- A Copy Constructor is a constructor used to create a new object by copying the data of an existing object of the same class.
Why MUST We Pass the Argument by Reference (&)?
- ⚠️ TOP #1 EXAM & VIVA QUESTION:
- Why is the copy constructor written as
Point(const Point &p)and NOTPoint(Point p)? - If you pass by value (
Point p), C++ must make a copy of the incoming object to pass it into the constructor. - But how does C++ make a copy?
- To call that copy constructor, it must again make a copy of its argument…
- This creates an infinite recursive loop of constructor calls!
When is a Copy Constructor Automatically Called?
- The C++ compiler automatically runs the copy constructor in 3 situations:
- When you create an object from another object:
Point p2 = p1;orPoint p2(p1);. - When an object is passed by value into a function.
- When an object is returned by value from a function.
The Big Problem: Shallow Copy vs. Deep Copy
- If you don’t write your own copy constructor, C++ provides a default one.
- Shallow Copy (Compiler Default) Just copies the pointer address.
- Deep Copy (Our Custom Solution) Allocates a brand new, independent block of heap memory using new , and copies the actual data over.
View diagram · Shallow Copy vs. Deep Copy Memory Architecture View diagram · Shallow Copy vs Deep Copy in C++
Dynamic Constructors in C++
- A Dynamic Constructor is a constructor that uses the
newoperator inside its body to allocate memory from the heap dynamically at…
Destructors in C++: Memory Cleanup & Order of Invocation
Overview: A local object’s destructor runs when control leaves its scope, including normal exception unwinding.
What is a Destructor?
- When you create an object, the Constructor sets up variables and allocates memory.
- Object Created Student s1; Constructor: Allocates memory & initializes variables.
- Object Goes Out of Scope Closing brace } reached Destructor: Frees memory & cleans up resources!
View diagram · Lifecycle of an Object
Key Characteristics of Destructors (Golden Exam Points)
- Tilde Symbol (
~): It has the exact same name as the class, but starts with a tilde symbol (~) (e.g. - Takes No Arguments: A destructor never takes any parameters.
- Cannot be Overloaded: Because it takes no arguments, a class can have ONLY ONE destructor!
- No Return Type: Just like constructors, it has no return type, not even
void. - Called Automatically: The compiler calls it automatically when an object reaches the end of its block
{}. - Can be Virtual: Unlike constructors (which cannot be virtual), Destructors CAN be declared
virtual(important when working with…
Order of Constructor and Destructor Execution (LIFO Rule)
- ⚠️ GOLDEN EXAM RULE:
- In C++, constructors run in normal order (first created, first initialized).
- Destructors ALWAYS run in the EXACT REVERSE order: Last In, First Out (LIFO)!
Comparison: Constructors vs. Destructors
- Name:
ClassName() - When does it run?: When an object is created
- Main Job: Allocates memory & initializes variables
- Overloading: Yes! Can have multiple constructors
- Arguments: Can accept 0, 1, or multiple parameters
- Can it be Virtual?: No