3 Constructors And Destructors

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.

Constructors and Destructors: notes

Constructor definition and purpose

A constructor is a special member function that runs automatically when an object is created. Its purpose is to initialise the data members.

Its special features are:

  • It has the same name as the class.
  • It has no return type, not even void.
  • It is normally public.
  • It is called automatically at object creation.
  • It can take arguments and can be overloaded.
  • It cannot be inherited, and it cannot be virtual.
class Counter {
    int count;
public:
    Counter() { count = 0; }      // constructor
    void show() { cout << count; }
};
Counter c;       // constructor runs here, count becomes 0

Types of constructors: default, parameterized, copy

Default constructor takes no arguments. If we write no constructor, the compiler gives one, but it does not set values.

Parameterized constructor takes arguments so each object can start with different values.

Copy constructor creates a new object as a copy of an existing object. Its form is ClassName(const ClassName &obj). The parameter must be a reference. Otherwise it would call itself forever.

class Point {
    int x, y;
public:
    Point() { x = y = 0; }                       // default
    Point(int a, int b) { x = a; y = b; }        // parameterized
    Point(const Point &p) { x = p.x; y = p.y; }  // copy
    void show() { cout << x << "," << y << endl; }
};

int main() {
    Point p1;            // default
    Point p2(3, 4);      // parameterized
    Point p3(p2);        // copy constructor
    Point p4 = p2;       // copy constructor again
}

The copy constructor runs when an object is made from another object. It also runs when an object is passed or returned by value. If the class holds a pointer, we write our own copy constructor to avoid sharing memory (a deep copy).

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 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

ConstructorParametersPurpose
Student()NoneDefault values assigned
Student(int, string)id, namePartial initialization
Student(int, string, float[], int)id, name, marks array and countComplete initialization at the time of object creation

Key Points Demonstrated

FeatureWhere it appears in the program
Constructor overloadingThree constructors share the name Student but differ in their parameter lists
Compile time polymorphismThe compiler picks the constructor by matching the argument list, so the choice is made at compile time, not at run time
Data hidingid, name and marks are private and are reached only through the member functions
Member functionsreadDetails() takes input, displayDetails() prints the record and calculateAverage() returns the average
Automatic invocationNo 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.

Open this answer on its own page →

2080.1 · 5 marks

What is constructor? Write a program to demonstrate constructor overloading in C++. [1+4]

A constructor is a special member function of a class that is automatically called when an object of that class is created. It has the same name as the class and has no return type (not even void). Its main purpose is to initialize the data members of an object. Key features: - Same name as the c...

Open this answer on its own page →

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 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:

  1. Base class constructor executes first
  2. 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:

AspectDetail
Base constructor callAlways called before derived constructor
SyntaxDerived(params) : Base(args) { }
Default base constructorCalled automatically if not specified
Destructor orderReverse 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.

Open this answer on its own page →

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]

--- --- Field t1 t2 Raw Sum Carry Final ---------------------------------------- Seconds 30 45 75 1 min 15 Minutes 45 20 65 + 1 = 66 1 hr 06 Hours 5 6 11 + 1 = 12 -- 12 Result: 12:06:15 -- correct. --- Concept Detail ------ Default Constructor Sets hours = minutes = seconds = 0 Parameterized Cons...

Open this answer on its own page →

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]

A class in C++ is a user-defined data type that bundles data members and member functions together. A constructor is a special member function that is automatically called when an object is created, used to initialize data members. --- --- --- Concept Description ------ Data Members customerId, n...

Open this answer on its own page →

Types of constructors

2078 · 5 marks

Describe types of constructors with an example. [5]

A constructor is a special member function that has the same name as the class, has no return type, and is automatically called when an object is created. --- A constructor that takes no parameters. It is called automatically when an object is created without any arguments. --- A constructor that...

Open this answer on its own page →

Destructor definition and characteristics

0 · 5 marks

What is destructor? Discuss its characteristics with suitable example. [5]

A destructor is a special member function of a class that is automatically called when an object goes out of scope or is explicitly deleted. It is used to release resources (such as memory, file handles, etc.) that were acquired by the object during its lifetime. --- Characteristic --------------...

Open this answer on its own page →