Chapter 4: Constructor and Destructor Class 12 Computer Science NCERT Solutions

Chapter 4 focuses on the crucial OOP concepts of constructors and destructors in C++. These special member functions play a vital role in object creation and destruction. Understanding how to properly use constructors and destructors enables students to initialize objects correctly and manage memory efficiently.

This chapter introduces the different types of constructors, including default, parameterized, copy constructors, and the importance of destructors in releasing resources. It helps students grasp how constructors and destructors work with dynamic memory allocation and object-oriented practices.

What You Will Learn in Chapter 4

This chapter teaches students how constructors and destructors are used to initialize and clean up objects in C++. It covers the syntax and behavior of different constructors, the need for destructors, and their role in managing resources like memory, files, and other system resources.

Key Topics Covered

Introduction to Constructors and Destructors

  • Constructors: Special member function called automatically when an object is created.

  • Destructors: Special member function called when an object goes out of scope or is explicitly deleted.

  • Purpose of constructors: Initialize objects with default or user-specified values.

  • Purpose of destructors: Release resources or memory allocated during object lifetime.

Types of Constructors

  • Default Constructor: A constructor that takes no arguments and initializes an object with default values.

  • Parameterized Constructor: A constructor that accepts parameters to initialize an object with specific values at the time of creation.

  • Copy Constructor: A constructor that creates a new object as a copy of an existing object, often used when passing objects by value to functions.

  • Constructor Overloading: Defining multiple constructors with different parameter lists to initialize objects in different ways.

Destructor

  • Syntax and function of destructors: A destructor does not take any parameters and cannot be overloaded.

  • Role of destructors: Automatically invoked when an object is destroyed, typically used for cleaning up resources (like memory deallocation).

  • Destructor behavior in dynamic memory allocation and deallocation.

Constructor and Destructor in Class Hierarchies

  • Calling base class constructor and destructor in derived classes.

  • Order of constructor and destructor calls in class hierarchies.

  • How constructors and destructors work in inheritance scenarios (calling parent constructors and destructors).

Dynamic Memory Allocation with Constructor and Destructor

  • Using new and delete operators for dynamic memory allocation and deallocation in constructors and destructors.

  • Ensuring proper memory management when creating objects dynamically.

Constructor and Destructor in Practice

  • Writing and understanding real-world examples of constructor and destructor use cases.

  • Practical applications like managing file resources, memory management, etc.

Download Chapter 4 Solutions PDF – Constructor and Destructor

Our downloadable PDF includes:

  • Complete NCERT textbook solutions for all questions with detailed explanations.

  • Example programs demonstrating different types of constructors and destructors.

  • Diagrams illustrating constructor/destructor relationships in class hierarchies.

  • Step-by-step solutions to common memory allocation/deallocation problems.

  • Syntax charts for constructor and destructor types.

Highlights of Our NCERT Solutions

  • Clear explanations with real C++ code examples for each type of constructor and destructor.

  • Visual diagrams showing the constructor and destructor flow in inheritance.

  • Practical examples involving dynamic memory management.

  • Easy-to-follow steps for implementing object initialization and cleanup.

  • Debugging tips for handling memory leaks and destructor issues.

Recommended Preparation Tips

  • Practice writing different types of constructors: default, parameterized, copy.

  • Learn how to manage memory using new and delete in constructors and destructors.

  • Revise the role of destructors in cleaning up dynamically allocated memory.

  • Understand the order of constructor and destructor calls in derived classes.

  • Experiment with constructor overloading and memory deallocation.

Additional Study Resources

  • Flashcards: Constructor types, destructor usage, and dynamic memory operations.

  • Worksheets: Code practice on creating objects and managing resources using constructors and destructors.

  • Diagrams: Visual flow of constructor and destructor calls in class hierarchies.

  • Practice questions on memory management and constructor/destructor issues.

  • CBSE sample papers and PYQs with constructor/destructor-based questions.

Mastering Chapter 4 – Constructor and Destructor

Mastery of constructors and destructors ensures students can effectively handle memory management and object initialization in object-oriented programming. Proper use of constructors and destructors leads to more efficient, bug-free programs that are easier to maintain.

This chapter is crucial for handling complex real-world applications involving resource management, inheritance, and dynamic memory allocation in C++.

Short Answer Type Questions – Chapter 4: Constructor and Destructor

Question 1: Write four characteristics of constructor function used in a class. [Delhi, 2014]

1. A constructor function has no return type. 2. Name of constructor is same as that of class. 3. A constructor can be called while creating objects. 4. If there is no constructor declared in class then default constructor is invoked.

Question 2: What is a copy constructor? Give a suitable example in C++ to illustrate with its definition within a class and a declaration of an object with the help of it. [Delhi, 2015]

A copy constructor is an overloaded constructor in which an object of the same class is passed as a reference parameter.
class Point {
    int x;
public:
    Point() { x = 0; }
    Point(Point &p) { // Copy constructor
        x = p.x;
    }
};

void main() {
    Point p1;
    Point p2(p1);   // Copy constructor is called
    // OR
    Point p3 = p1;  // Also calls the copy constructor
}

Question 3: Answer the questions (i) and (ii) after going through the following class: [Delhi, 2015]

class Exam {
    int Rollno;
    char Cname[25];
    float Marks;
public:
    Exam() {
        Rollno = 0;
        strcpy(Cname, " ");
        Marks = 0.0;
    }
    Exam(int Rno, char candname[]) {
        Rollno = Rno;
        strcpy(Cname, candname);
    }
    ~Exam() {
        cout << "Result will be intimated shortly" << endl;
    }
    void Display() {
        cout << "Roll no: " << Rollno;
        cout << "Name: " << Cname;
        cout << "Marks: " << Marks;
    }
};
(i) Which OOP concept does Function 1 and Function 2 implement? Answer: Constructor Overloading (Polymorphism). Function 1 is a default constructor and Function 2 is a parameterized constructor. (ii) What is Function 3 called? When will it be invoked? Answer: Function 3 is a Destructor. It will be invoked when the object goes out of scope.

Question 4: Answer the questions (i) and (ii) after going through the following class:

class Planet {
    char name[20];
    char distance[20];
public:
    Planet() {
        strcpy(name, "Venus");
        strcpy(distance, "38 million km");
    }
    void display(char na[], char d[]) {
        cout << na << " has " << d << " distance from Earth" << endl;
    }
    Planet(char na[], char d[]) {
        strcpy(name, na);
        strcpy(distance, d);
    }
    ~Planet() {
        cout << "Planetarium time over !!!" << endl;
    }
};
(i) What is Function 1 referred as? When will it be executed? Answer: Function 1 is a Constructor. It is executed at the time of object creation. (ii) Write suitable C++ statement to invoke Function 2. Answer:
Planet p;
p.display("Pluto", "7.5 Billion Km");

Question 5: Observe the following C++ code and answer the questions: [O.D, 2015]

class Passenger {
    long PNR;
    char Name[20];
public:
    Passenger() {
        cout << "Ready" << endl;
    }
    void Book(long P, char N[]) {
        PNR = P;
        strcpy(Name, N);
    }
    void Print() {
        cout << PNR << Name << endl;
    }
    ~Passenger() {
        cout << "Booking cancelled!" << endl;
    }
};
(i) Fill in Line 1 and Line 2:
void main() {
    Passenger P;
    P.Book(1234567, "Ravi"); // Line 1
    P.Print();               // Line 2
}
(ii) Which function will be executed at the end of main()? What is it called? Answer: ~Passenger() will be executed. It is called a Destructor.

Question 6: Answer the questions (i) and (ii) after going through the following class: [CBSE SQP, 2015]

class Stream {
    int StreamCode;
    char Streamname[20];
    float fees;
public:
    Stream() {
        StreamCode = 1;
        strcpy(Streamname, "DELHI");
        fees = 1000;
    }
    void display(float C) {
        cout << StreamCode << ":" << Streamname << fees << endl;
    }
    ~Stream() {
        cout << "End of Stream Object" << endl;
    }
    Stream(int SC, char S[], float F); // Function 4
};
(i) What are Function 1 and Function 4 together referred as? Answer: Constructor Overloading Definition of Function 4:
Stream::Stream(int Sc, char S[], float F) {
    StreamCode = Sc;
    strcpy(Streamname, S);
    fees = F;
}
(ii) Difference between: Stream S(11, "Science", 8700); → Implicit constructor call Stream S = Stream(11, "Science", 8700); → Explicit constructor call

Question 7: Answer the question (i) and (ii) after going through the following class: [CBSE Comptt., 2013]

class Book {
    int BookNo;
    char BookTitle[20];
public:
    Book();               // Function 1
    Book(Book &);         // Function 2
    Book(int, char[]);    // Function 3
    void Buy();           // Function 4
    void Sell();          // Function 5
};
(i) Name the OOP feature demonstrated by Function 1, 2, and 3: Answer: Constructor Overloading (ii) Write statements to execute Function 3 and 4 inside main():
void main() {
    Book B(5, "Jay");
    B.Buy();
}

Question 8: Answer the questions (i) and (ii) after going through the following class: [O.D., 2013]

class Race {
    int CarNo, Track;
public:
    Race();              // Function 1
    Race(int CN);        // Function 2
    Race(Race &R);       // Function 3
    void Register();     // Function 4
    void Drive();        // Function 5
};

void main() {
    Race R;
}
(i) Correct way of calling Function 2: Answer: Option 1 – Race T(30); (ii) OOP concept demonstrated by Function 1, 2 and 3: Answer: Constructor Overloading (Polymorphism)

Question 9: Answer the questions (i) and (ii) after going through the following class:

class Motor {
    int MotorNo, Track;
public:
    Motor();                   // Function 1
    Motor(int MN);             // Function 2
    Motor(Motor & M);          // Function 3
    void Allocate();           // Function 4
    void Move();               // Function 5
};

void main() {
    Motor M;
}
(i) Correct option for calling Function 2: Answer: Option 2 — Motor P(10); (ii) Feature of Object-Oriented Programming demonstrated: Answer: Constructor Overloading (Polymorphism)

Question 10: What is constructor overloading? Give an example to illustrate the same. [CBSE SQP 2013]

Answer: Constructor Overloading is the process of defining multiple constructors in the same class with different parameter lists. This allows object creation using different arguments. Example:
class Circle {
    int radius;
public:
    Circle() {               // Default Constructor
        radius = 0;
    }
    Circle(int r) {          // Overloaded Constructor
        radius = r;
    }
};

Question 11: What is a Copy Constructor? Give a suitable example using a class in C++. [CBSE Comptt. 2016]

Answer: A Copy Constructor is a special constructor used to create a new object as a copy of an existing object. It takes a reference to an object of the same class as its parameter. Syntax: ClassName(ClassName &) This is done to avoid recursive constructor calls during the copying process. Example:
class Sample {
    int i, j;
public:
    Sample(int a, int b) {     // Parameterized Constructor
        i = a; j = b;
    }
    Sample(Sample &s) {        // Copy Constructor
        i = s.i;
        j = s.j;
        cout << "Copy constructor working" << endl;
    }
    void print() {
        cout << i << " " << j << endl;
    }
};

int main() {
    Sample s1(10, 20);
    Sample s2(s1);  // Copy constructor is called
    s2.print();
    return 0;
}
Note: The copy constructor must take its argument by reference to avoid infinite recursion.

Question 12: Observe the following C++ code and answer the questions (i) and (ii). (Assume all required files are included)

class COMIC {
    long CCode;
    char CTitle[20];
    float CPrice;
public:
    COMIC() {
        cout << "got..." << endl;
        CCode = 100;
        strcpy(CTitle, "Unknown");
        CPrice = 100;
    }
    COMIC(int C, char T[], float P) {
        CCode = C;
        strcpy(CTitle, T);
        CPrice = P;
    }
    void Raise(float P) {
        CPrice += P;
    }
    void Disp() {
        cout << CCode << ";" << CTitle << ";" << CPrice << endl;
    }
    ~COMIC() {
        cout << "COMIC Discarded!" << endl;
    }
};

void main() {
    COMIC C1, C2(1001, "Tom and Jerry", 75);
    for (int I = 0; I < 4; I++) {
        C1.Raise(20);
        C2.Raise(15);
        C1.Disp();
        C2.Disp();
    }
}
(i) Which concept of Object-Oriented Programming is illustrated by Member Function 1 and Member Function 2 combined? Answer: Polymorphism (specifically Constructor Overloading) (ii) How many times will the message “COMIC Discarded!” be displayed after executing the program? Which line(s) are responsible? Answer: 2 times – one for each object (C1 and C2). Responsible line: End of main() function when both objects go out of scope.


Short Answer Type Questions-II (3 Marks Each)

Question 1: Write any two similarities between Constructors and Destructors. Write the Function headers for constructor and destructor of a class Flight. [Outside Delhi, 2013]

Answer:

Similarities:

  • Both have the same name as the class.
  • Both are used to handle the objects of a class.

Function Headers:
Constructor: Flight()
Destructor: ~Flight()

Question 2: Write any two differences between Constructors and Destructors. Write the function headers for constructor and destructor of a class Member. [Delhi, 2013]

Answer:

ConstructorDestructor
Invoked every time when the object is created.Invoked every time when the object goes out of scope.
Used to construct and initialize object values.Used to destroy objects and release memory.

Function Headers:
Constructor: Member()
Destructor: ~Member()

Question 3: Answer the following questions (i) and (ii) after going through the following class:

class Tour {
    int LocationCode;
    char Location[20];
    float Charges;
public:
    Tour() {
        LocationCode = 1;
        strcpy(Location, "PURI");
        Charges = 1200;
    }
    void TourPlan(float C) {
        cout << LocationCode << ":" << Location << ":" << Charges << endl;
        Charges += 100;
    }
    Tour(int LC, char L[], float C) {
        LocationCode = LC;
        strcpy(Location, L);
        Charges = C;
    }
    ~Tour() {
        cout << "TourPlan cancelled" << endl;
    }
};

(i) Function 1 and Function 3 together are known as: Constructor Overloading
(ii) Function 4 is a Destructor. It is invoked automatically when the object goes out of scope.

Question 4: Answer the following questions (i) and (ii) after going through the following class:

class Travel {
    int PlaceCode;
    char Place[20];
    float Charges;
public:
    Travel() {
        PlaceCode = 1;
        strcpy(Place, "DELHI");
        Charges = 1000;
    }
    void TravelPlan(float C) {
        cout << PlaceCode << ":" << Place << ":" << Charges << endl;
        Charges += 100;
    }
    ~Travel() {
        cout << "Travel Plan cancelled" << endl;
    }
    Travel(int PC, char P[], float C) {
        PlaceCode = PC;
        strcpy(Place, P);
        Charges = C;
    }
};

(i) Function 1 and Function 4 illustrate: Constructor Overloading
(ii) Function 3 is a Destructor and it is called automatically when the object goes out of scope.

Question 5: Answer the questions (i) and (ii) after going through the following:

class schoolbag {
    int pockets;
public:
    schoolbag() {
        pockets = 30;
        cout << "The bag has pockets" << endl;
    }
    void company() {
        cout << "The company of the Bag is ABC" << endl;
    }
    schoolbag(int D) {
        pockets = D;
        cout << "Now the Bag has pockets " << pockets << endl;
    }
    ~schoolbag() {
        cout << "Thanks" << endl;
    }
};

(i) Function 4 is a Destructor. It gets automatically invoked when the object goes out of scope.
(ii) Function 1 and Function 3 demonstrate Constructor Overloading.