Object Oriented Programming · Unit 3
Constructors and Destructors
Exam-focused notes for Constructors and Destructors (Object Oriented Programming, BIT153): what the TU syllabus asks and how it has actually been tested, with 7 solved past questions from this unit.
Constructors and Destructors in short
Constructors set up an object when it is created. Destructors clean up when it is destroyed. They make sure an object always starts and ends in a proper state.
What this unit covers
- Constructor definition and purpose
- Types of constructors: default, parameterized, copy
- Constructor overloading
- Initialization of data members
- Destructor definition and characteristics
- Constructor and destructor execution order
- Constructor invocation in derived classes
Constructor overloading
2082 · 10 marks
Write a program to create a class Student with data members id, name, and marks. Define constructors to initialize data members and demonstrate constructor overloading. Implement member functions to read students details, display them and calculate average marks.[10]
Show solved answerHide answer
Constructor Overloading with Student Class
Concept
Constructor overloading means defining multiple constructors in the same class with different parameter lists. The compiler selects the appropriate constructor based on the arguments passed during object creation.
Complete C++ Program
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int id;
string name;
float marks[5]; // stores marks of 5 subjects
int numSubjects;
public:
// -----------------------------------------------
// Constructor 1: Default Constructor
// Initializes data members with default values
// -----------------------------------------------
Student() {
id = 0;
name = "Unknown";
numSubjects = 5;
for (int i = 0; i < numSubjects; i++) {
marks[i] = 0.0;
}
cout << "Default constructor called." << endl;
}
// -----------------------------------------------
// Constructor 2: Parameterized Constructor
// Initializes id and name; marks set to 0
// -----------------------------------------------
Student(int i, string n) {
id = i;
name = n;
numSubjects = 5;
for (int j = 0; j < numSubjects; j++) {
marks[j] = 0.0;
}
cout << "Parameterized constructor (id, name) called." << endl;
}
// -----------------------------------------------
// Constructor 3: Fully Parameterized Constructor
// Initializes all data members including marks
// -----------------------------------------------
Student(int i, string n, float m[], int num) {
id = i;
name = n;
numSubjects = num;
for (int j = 0; j < numSubjects; j++) {
marks[j] = m[j];
}
cout << "Fully parameterized constructor called." << endl;
}
// -----------------------------------------------
// Member Function: Read student details
// -----------------------------------------------
void readDetails() {
cout << "\nEnter Student ID : ";
cin >> id;
cout << "Enter Student Name : ";
cin.ignore();
getline(cin, name);
cout << "Enter marks for " << numSubjects << " subjects:" << endl;
for (int i = 0; i < numSubjects; i++) {
cout << " Subject " << (i + 1) << " : ";
cin >> marks[i];
}
}
// -----------------------------------------------
// Member Function: Display student details
// -----------------------------------------------
void displayDetails() {
cout << "\n--- Student Details ---" << endl;
cout << "ID : " << id << endl;
cout << "Name : " << name << endl;
cout << "Marks : ";
for (int i = 0; i < numSubjects; i++) {
cout << marks[i];
if (i < numSubjects - 1) cout << ", ";
}
cout << endl;
cout << "Average: " << calculateAverage() << endl;
cout << "-----------------------" << endl;
}
// -----------------------------------------------
// Member Function: Calculate average marks
// -----------------------------------------------
float calculateAverage() {
float sum = 0.0;
for (int i = 0; i < numSubjects; i++) {
sum += marks[i];
}
return sum / numSubjects;
}
};
// -----------------------------------------------
// Main Function: Demonstrates constructor overloading
// -----------------------------------------------
int main() {
cout << "========================================" << endl;
cout << " Constructor Overloading Demo " << endl;
cout << "========================================" << endl;
// Using Default Constructor
cout << "\n[Object 1: Default Constructor]" << endl;
Student s1;
s1.readDetails();
s1.displayDetails();
// Using Parameterized Constructor (id and name only)
cout << "\n[Object 2: Parameterized Constructor (id, name)]" << endl;
Student s2(102, "Ram Sharma");
s2.readDetails();
s2.displayDetails();
// Using Fully Parameterized Constructor
cout << "\n[Object 3: Fully Parameterized Constructor]" << endl;
float m[] = {78.5, 85.0, 90.0, 72.5, 88.0};
Student s3(103, "Sita Thapa", m, 5);
s3.displayDetails(); // no need to read; already initialized
return 0;
}
Sample Output
========================================
Constructor Overloading Demo
========================================
[Object 1: Default Constructor]
Default constructor called.
Enter Student ID : 101
Enter Student Name : Hari Bahadur
Enter marks for 5 subjects:
Subject 1 : 75
Subject 2 : 80
Subject 3 : 65
Subject 4 : 90
Subject 5 : 70
--- Student Details ---
ID : 101
Name : Hari Bahadur
Marks : 75, 80, 65, 90, 70
Average: 76
-----------------------
[Object 2: Parameterized Constructor (id, name)]
Parameterized constructor (id, name) called.
...
[Object 3: Fully Parameterized Constructor]
Fully parameterized constructor called.
--- Student Details ---
ID : 103
Name : Sita Thapa
Marks : 78.5, 85, 90, 72.5, 88
Average: 82.8
-----------------------
Summary Table
| Constructor | Parameters | Purpose |
|---|---|---|
Student() | None | Default values assigned |
Student(int, string) | id, name | Partial initialization |
Student(int, string, float[], int) | id, name, marks array and count | Complete initialization at the time of object creation |
Key Points Demonstrated
| Feature | Where it appears in the program |
|---|---|
| Constructor overloading | Three constructors share the name Student but differ in their parameter lists |
| Compile time polymorphism | The compiler picks the constructor by matching the argument list, so the choice is made at compile time, not at run time |
| Data hiding | id, name and marks are private and are reached only through the member functions |
| Member functions | readDetails() takes input, displayDetails() prints the record and calculateAverage() returns the average |
| Automatic invocation | No constructor is ever called by name; each runs the moment its object is created |
The three constructors are legal together because their signatures differ, Student(), Student(int, string) and Student(int, string, float[], int), and an overload set is resolved on the number and the type of the arguments only. Note that a return type may not be used to distinguish them, since a constructor has no return type at all.
The average is computed as:
$$\text{Average} = \frac{\sum_{i=1}^{n} marks_i}{n}$$
so for the third object the average is (78.5 + 85 + 90 + 72.5 + 88) / 5, which is 82.8 as printed in the sample output.
Conclusion
The program defines a Student class with private data members and three overloaded constructors, then creates one object through each of them to show that the compiler selects the constructor from the argument list. Together with the member functions for reading, displaying and averaging the marks, it demonstrates encapsulation and compile time polymorphism in a single, exam-ready example.
2080.1 · 5 marks
What is constructor? Write a program to demonstrate constructor overloading in C++. [1+4]
Constructor definition and purpose
2080 · 10 marks
What is constructor? Explain its types with suitable example.How is the constructor called in a derived class in C++?[6+4]
Show solved answerHide answer
Constructor in C++
What is a Constructor?
A constructor is a special member function of a class that is automatically called when an object of that class is created. It is used to initialize the data members of the class.
Key Characteristics:
- Has the same name as the class
- Has no return type (not even
void) - Called automatically when an object is created
- Can be overloaded
Types of Constructors
1. Default Constructor
A constructor that takes no arguments. If no constructor is defined, the compiler provides one automatically.
#include<iostream>
using namespace std;
class Student {
int roll;
string name;
public:
// Default Constructor
Student() {
roll = 0;
name = "Unknown";
cout << "Default Constructor called" << endl;
}
void display() {
cout << "Roll: " << roll << ", Name: " << name << endl;
}
};
int main() {
Student s1; // Default constructor called automatically
s1.display();
return 0;
}
Output:
Default Constructor called
Roll: 0, Name: Unknown
2. Parameterized Constructor
A constructor that accepts one or more arguments to initialize objects with specific values.
#include<iostream>
using namespace std;
class Student {
int roll;
string name;
public:
// Parameterized Constructor
Student(int r, string n) {
roll = r;
name = n;
cout << "Parameterized Constructor called" << endl;
}
void display() {
cout << "Roll: " << roll << ", Name: " << name << endl;
}
};
int main() {
Student s1(101, "Ram"); // Parameterized constructor called
s1.display();
return 0;
}
Output:
Parameterized Constructor called
Roll: 101, Name: Ram
3. Copy Constructor
A constructor that creates a new object as a copy of an existing object. It takes a reference to an object of the same class as its argument.
#include<iostream>
using namespace std;
class Student {
int roll;
string name;
public:
Student(int r, string n) {
roll = r;
name = n;
}
// Copy Constructor
Student(const Student &s) {
roll = s.roll;
name = s.name;
cout << "Copy Constructor called" << endl;
}
void display() {
cout << "Roll: " << roll << ", Name: " << name << endl;
}
};
int main() {
Student s1(101, "Ram");
Student s2(s1); // Copy constructor called
s2.display();
return 0;
}
Output:
Copy Constructor called
Roll: 101, Name: Ram
4. Constructor Overloading
Multiple constructors with different parameter lists in the same class.
#include<iostream>
using namespace std;
class Rectangle {
float length, breadth;
public:
Rectangle() { // Default
length = breadth = 0;
}
Rectangle(float l, float b) { // Parameterized
length = l;
breadth = b;
}
void area() {
cout << "Area = " << length * breadth << endl;
}
};
int main() {
Rectangle r1; // calls default constructor
Rectangle r2(5.0, 3.0); // calls parameterized constructor
r1.area();
r2.area();
return 0;
}
Calling Constructor in a Derived Class
When a derived class object is created, both the base class constructor and the derived class constructor are called. The base class constructor is called first, then the derived class constructor.
To explicitly pass arguments to the base class constructor, we use an initializer list with the colon (:) syntax.
Syntax:
DerivedClass(parameters) : BaseClass(arguments) {
// derived class constructor body
}
Order of Execution:
- Base class constructor executes first
- Derived class constructor executes next
Example:
#include<iostream>
using namespace std;
// Base Class
class Animal {
string name;
public:
Animal(string n) {
name = n;
cout << "Animal Constructor: " << name << endl;
}
};
// Derived Class
class Dog : public Animal {
string breed;
public:
// Calling base class constructor using initializer list
Dog(string n, string b) : Animal(n) {
breed = b;
cout << "Dog Constructor: Breed = " << breed << endl;
}
};
int main() {
Dog d1("Tommy", "Labrador");
return 0;
}
Output:
Animal Constructor: Tommy
Dog Constructor: Breed = Labrador
Key Points:
| Aspect | Detail |
|---|---|
| Base constructor call | Always called before derived constructor |
| Syntax | Derived(params) : Base(args) { } |
| Default base constructor | Called automatically if not specified |
| Destructor order | Reverse of constructor order |
Note: If the base class has only a parameterized constructor (no default constructor), the derived class must explicitly call it using the initializer list, otherwise a compile-time error occurs.
2078 · 10 marks
Create a class called time that has separate int member data for hours, minutes, and seconds. One constructor should initialize this data to 0, and another should initialize it to fixed values. Another member function should display it, in 11:59:59 format. The final member function should add two objects of type time passed as arguments. A main() program should create two initialized time objects (should they be const) and one that isn't initialized. Then it should add the two initialized values together, leaving the result in the third time variable. Finally, it should display the value of this third variable Make appropriate member functions const.[10]
0 · 10 marks
Write a program to create a class Customer with data members customer Id, Name, and age. Put member functions to read and display values of data members. Also define constructors to initialize data members with default value. Finally create object to read and display data of 10 customers.[10]
Types of constructors
Destructor definition and characteristics
0 · 5 marks
What is destructor? Discuss its characteristics with suitable example. [5]
Make Unit 3 stick
Practice BIT153 with flashcards & quizzes