ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCSI-312Constructors And Destr…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CSI-312

    Object Oriented Programming

    Progress0 / 16 done
    Topics16
    1Evolution of Object-Oriented (OO) Programming2Object-Oriented (OO) Concepts and Principles3Problem Solving in OO Paradigm4OO Programme Design Process5Classes6Methods7Objects and Encapsulation8Constructors and Destructors9Operator Overloading10Function Overloading11Virtual Functions12Derived Classes13Inheritance14Polymorphism15I/O and File Processing16Exception Handling
    8 min read
    Topic 8 of 16
    Topic Study Note Illustration
    08

    Constructors and Destructors

    In Object-Oriented Programming (OOP), constructors and destructors are special member functions of a class. They play a key role in managing an object's lifecycle— constructors initialize objects,...

    Constructors and Destructors in Object-Oriented Programming (OOP)

    In Object-Oriented Programming (OOP), constructors and destructors are special member functions of a class. They play a key role in managing an object's lifecycle—constructors initialize objects, while destructors clean up resources when objects are destroyed. These functions help automate memory management and ensure that objects are properly initialized and cleaned up.


    1. Constructors

    A constructor is a special member function that is automatically called when an object of a class is created. The primary purpose of a constructor is to initialize the object, i.e., to assign values to its data members (attributes) when it is created. Constructors can also perform any other necessary setup or preparation tasks.

    Key Characteristics of Constructors:

    • Name: A constructor has the same name as the class.
    • No Return Type: Constructors do not have a return type, not even void.
    • Automatic Invocation: A constructor is called automatically when an object is created, and it is not called explicitly by the user.
    • Overloading: In C++, constructors can be overloaded, meaning you can have multiple constructors with different parameter lists.

    Types of Constructors:

    1. Default Constructor: A constructor that takes no arguments. If no constructor is provided, C++ automatically provides a default constructor.
    2. Parameterized Constructor: A constructor that takes one or more arguments to initialize an object with specific values.
    3. Copy Constructor: A constructor used to create a new object that is a copy of an existing object.

    Example of Constructors:

    #include <iostream>
    using namespace std;
    
    class Car {
    private:
        string model;
        int year;
    
    public:
        // Default constructor (no parameters)
        Car() {
            model = "Unknown";
            year = 0;
            cout << "Default Constructor Called" << endl;
        }
    
        // Parameterized constructor
        Car(string m, int y) {
            model = m;
            year = y;
            cout << "Parameterized Constructor Called" << endl;
        }
    
        // Method to display car details
        void displayInfo() {
            cout << "Model: " << model << ", Year: " << year << endl;
        }
    };
    
    int main() {
        Car car1;  // Default constructor
        car1.displayInfo();
    
        Car car2("Tesla Model S", 2022);  // Parameterized constructor
        car2.displayInfo();
    
        return 0;
    }
    

    Explanation:

    • Car() is the default constructor. It initializes the object's model to "Unknown" and year to 0.
    • Car(string m, int y) is the parameterized constructor that allows the user to specify the model and year during object creation.
    • When car1 is created, the default constructor is invoked, and when car2 is created, the parameterized constructor is used.

    2. Destructors

    A destructor is a special member function that is called when an object goes out of scope or is explicitly deleted. The purpose of the destructor is to release resources that the object may have acquired during its lifetime, such as memory, file handles, or network connections. Destructors help prevent memory leaks by ensuring that resources are properly cleaned up when an object is destroyed.

    Key Characteristics of Destructors:

    • Name: A destructor has the same name as the class but is preceded by a tilde (~) symbol.
    • No Return Type: Like constructors, destructors do not have a return type.
    • Automatic Invocation: A destructor is called automatically when an object is destroyed (either when it goes out of scope or when delete is called).
    • No Arguments: Destructors cannot take any parameters, and they cannot be overloaded.

    Example of Destructors:

    #include <iostream>
    using namespace std;
    
    class Car {
    private:
        string model;
        int year;
    
    public:
        // Constructor
        Car(string m, int y) {
            model = m;
            year = y;
            cout << "Car object created: " << model << " (" << year << ")" << endl;
        }
    
        // Destructor
        ~Car() {
            cout << "Car object destroyed: " << model << " (" << year << ")" << endl;
        }
    
        // Method to display car details
        void displayInfo() {
            cout << "Model: " << model << ", Year: " << year << endl;
        }
    };
    
    int main() {
        // Creating a car object (constructor is called)
        Car car1("Honda Civic", 2021);
        car1.displayInfo();  // Output car details
    
        // When the program ends, car1 goes out of scope, and the destructor is called
        return 0;  // Destructor automatically called here
    }
    

    Explanation:

    • The constructor initializes the model and year of the car and displays a message.
    • The destructor prints a message when the object is destroyed. When car1 goes out of scope at the end of the main() function, the destructor is automatically invoked.
    • The destructor ensures that any necessary cleanup tasks are performed when the object is destroyed.

    Copy Constructor

    The copy constructor is a special type of constructor that is used to create a new object as a copy of an existing object. It is called when:

    • An object is passed by value to a function.
    • An object is returned by value from a function.
    • An object is explicitly copied (e.g., Car car2 = car1;).

    By default, C++ performs a shallow copy (bitwise copy) when creating a copy of an object. However, this might not be sufficient if the object contains dynamically allocated memory or complex resources. In such cases, you may need to implement a deep copy.

    Example of a Copy Constructor:

    #include <iostream>
    using namespace std;
    
    class Car {
    private:
        string model;
        int year;
    
    public:
        // Constructor
        Car(string m, int y) {
            model = m;
            year = y;
            cout << "Car created: " << model << " (" << year << ")" << endl;
        }
    
        // Copy Constructor
        Car(const Car &other) {
            model = other.model;  // Copy model from another car
            year = other.year;    // Copy year from another car
            cout << "Car copied: " << model << " (" << year << ")" << endl;
        }
    
        // Method to display car details
        void displayInfo() {
            cout << "Model: " << model << ", Year: " << year << endl;
        }
    };
    
    int main() {
        Car car1("Toyota Corolla", 2020);
        car1.displayInfo();
    
        // Using the copy constructor
        Car car2 = car1;  // Copy constructor is called
        car2.displayInfo();
    
        return 0;
    }
    

    Explanation:

    • The copy constructor creates a new Car object (car2) by copying the attributes (model and year) of car1.
    • The constructor Car(const Car &other) is invoked when car2 is created as a copy of car1.

    Destructor and Memory Management

    In C++, if your class dynamically allocates memory (e.g., using new), you need to ensure that this memory is released when the object is destroyed. This is where the destructor comes in. For example:

    Example with Dynamic Memory Allocation:

    #include <iostream>
    using namespace std;
    
    class Car {
    private:
        string* model;
        int year;
    
    public:
        // Constructor
        Car(string m, int y) {
            model = new string(m);  // Dynamically allocate memory for model
            year = y;
            cout << "Car created: " << *model << " (" << year << ")" << endl;
        }
    
        // Destructor
        ~Car() {
            delete model;  // Free the dynamically allocated memory
            cout << "Car destroyed and memory released" << endl;
        }
    
        // Method to display car details
        void displayInfo() {
            cout << "Model: " << *model << ", Year: " << year << endl;
        }
    };
    
    int main() {
        Car car1("Honda Civic", 2022);
        car1.displayInfo();  // Output car details
    
        return 0;  // Destructor automatically called here, memory released
    }
    

    Explanation:

    • In this example, memory for the model attribute is dynamically allocated using new in the constructor.
    • The destructor ensures that this memory is properly freed with the delete keyword when the object is destroyed.
    • This prevents memory leaks, which can occur if dynamically allocated memory is not deallocated.

    Summary of Constructors and Destructors:

    1. Constructors:

      • Automatically invoked when an object is created.
      • Used to initialize object attributes.
      • Can be overloaded (multiple constructors with different parameters).
    2. Destructors:

      • Automatically invoked when an object is destroyed (goes out of scope or is deleted).
      • Used for cleanup tasks like releasing dynamically allocated memory or closing files.
      • Cannot be overloaded and do not take parameters.
    3. Copy Constructors:

      • Special constructors that create a copy of an existing object.
      • Important when dealing with objects that manage resources like dynamic memory.

    By using

    ← Previous topic 7
    Objects and Encapsulation
    Next topic 9 →
    Operator Overloading

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    8mremaining
    1.4kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Object Oriented Programming