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 PortalCC-211Constructors And Destr…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-211

    Object Oriented Programming

    Progress0 / 24 done
    Topics24
    1History and Advantages
    2Terminology and Features3Classes and Objects4Data Encapsulation5Constructors and Destructors6Access Modifiers7Const vs Non-Const Functions8Static Data Members and Functions9Function Overloading10Operator Overloading11Identification of Classes and Their Relationships12Composition13Aggregation14Inheritance15Multiple Inheritances16Polymorphism17Abstract Classes18Interfaces19Generic Programming Concepts20Function Templates21Class Templates22Standard Template Library
    23Data and Object Serialization24Exception Handling
    7 min read
    Topic 5 of 24
    Topic Study Note Illustration
    05

    Constructors and Destructors

    In Object-Oriented Programming (OOP), constructors and destructors are special member functions used for managing the lifecycle of objects. They play a crucial role in object initialization and...

    Constructors and Destructors in Object-Oriented Programming (OOP)

    In Object-Oriented Programming (OOP), constructors and destructors are special member functions used for managing the lifecycle of objects. They play a crucial role in object initialization and cleanup.


    Constructors

    A constructor is a special member function that is automatically called when an object of a class is created. The main purpose of a constructor is to initialize the object's data members to a valid state. Constructors do not return any value, not even void.

    Key Features of Constructors:

    1. Automatic Invocation:

      • A constructor is invoked automatically when an object is created, so you don’t need to call it explicitly.
    2. No Return Type:

      • Constructors do not have a return type, not even void.
    3. Same Name as Class:

      • The constructor has the same name as the class in which it is defined.
    4. Overloading:

      • C++ allows constructor overloading, meaning you can have multiple constructors with different parameters in the same class.

    Types of Constructors:

    1. Default Constructor:

      • A constructor that takes no arguments. It initializes the object with default values.
      • Example: If you don’t explicitly pass any values, the default constructor will initialize the object with default or predefined values.
    2. Parameterized Constructor:

      • A constructor that takes arguments to initialize an object with specific values when it is created.
      • Example: You can pass values when creating an object, which the constructor uses to initialize the data members.
    3. Copy Constructor:

      • A constructor that creates a new object by copying an existing object of the same class. It is called when:
        • A new object is created as a copy of an existing object.
        • An object is passed by value to a function.
      • This constructor ensures that the copied object has the same state as the original.

    Example of Constructors in C++:

    #include <iostream>
    using namespace std;
    
    class Car {
    private:
        string brand;
        int year;
    
    public:
        // Default Constructor
        Car() {
            brand = "Unknown";
            year = 0;
        }
    
        // Parameterized Constructor
        Car(string b, int y) {
            brand = b;
            year = y;
        }
    
        // Copy Constructor
        Car(const Car &c) {
            brand = c.brand;
            year = c.year;
        }
    
        // Method to display details
        void displayDetails() {
            cout << "Brand: " << brand << ", Year: " << year << endl;
        }
    };
    
    int main() {
        // Creating an object using the default constructor
        Car car1;
        car1.displayDetails();
    
        // Creating an object using the parameterized constructor
        Car car2("Toyota", 2020);
        car2.displayDetails();
    
        // Creating an object using the copy constructor
        Car car3 = car2;  // Copy car2 to car3
        car3.displayDetails();
    
        return 0;
    }
    

    Explanation:

    • Default Constructor: The Car() constructor initializes brand to "Unknown" and year to 0.
    • Parameterized Constructor: The Car(string b, int y) constructor initializes the Car object with specific values for brand and year.
    • Copy Constructor: The Car(const Car &c) constructor creates a copy of an existing Car object (car2) and assigns its values to the new object (car3).

    Destructors

    A destructor is a special member function that is called automatically when an object goes out of scope or is explicitly deleted. The primary purpose of a destructor is to release resources (such as memory, file handles, or network connections) that were acquired during the lifetime of the object.

    Key Features of Destructors:

    1. Automatic Invocation:

      • A destructor is called automatically when an object is destroyed, either when it goes out of scope (for local objects) or when delete is called (for dynamically allocated objects).
    2. No Arguments:

      • A destructor cannot take any arguments and cannot return any value.
    3. Same Name as Class (with ~ prefix):

      • The destructor has the same name as the class, but with a tilde (~) prefix.
    4. Only One Destructor per Class:

      • A class can have only one destructor. It cannot be overloaded.
    5. Memory Cleanup:

      • Destructors are commonly used for cleaning up dynamically allocated memory or releasing other resources that the object may have acquired.

    Example of Destructors in C++:

    #include <iostream>
    using namespace std;
    
    class Car {
    private:
        string brand;
        int year;
    
    public:
        // Constructor to initialize the object
        Car(string b, int y) {
            brand = b;
            year = y;
            cout << "Car " << brand << " created." << endl;
        }
    
        // Destructor to clean up resources
        ~Car() {
            cout << "Car " << brand << " destroyed." << endl;
        }
    
        // Method to display car details
        void displayDetails() {
            cout << "Brand: " << brand << ", Year: " << year << endl;
        }
    };
    
    int main() {
        // Creating an object of Car
        Car car1("Toyota", 2020);
        car1.displayDetails();
    
        // Destructor is automatically called when car1 goes out of scope at the end of main
        return 0;
    }
    

    Explanation:

    • When the Car object car1 goes out of scope at the end of the main() function, the destructor ~Car() is automatically called to clean up any resources (in this case, just printing a message).
    • The destructor in this example doesn’t deal with memory cleanup or other complex resources but can be extended to handle resource management tasks such as freeing dynamically allocated memory.

    Destructor and Memory Management

    Destructors are particularly important when dealing with dynamic memory (memory allocated using new in C++). If objects dynamically allocate memory or other resources, the destructor ensures that these resources are properly freed when the object is destroyed.

    Example of Destructor with Dynamic Memory:

    #include <iostream>
    using namespace std;
    
    class Car {
    private:
        string *brand;
        int year;
    
    public:
        // Constructor to allocate memory for the brand
        Car(string b, int y) {
            brand = new string(b);  // Dynamically allocate memory
            year = y;
            cout << "Car " << *brand << " created." << endl;
        }
    
        // Destructor to release dynamically allocated memory
        ~Car() {
            delete brand;  // Free dynamically allocated memory
            cout << "Car memory for " << *brand << " destroyed." << endl;
        }
    
        // Method to display car details
        void displayDetails() {
            cout << "Brand: " << *brand << ", Year: " << year << endl;
        }
    };
    
    int main() {
        Car car1("Toyota", 2020);
        car1.displayDetails();
        // Destructor is automatically called when car1 goes out of scope
        return 0;
    }
    

    Explanation:

    • In this example, brand is a pointer to a string that is dynamically allocated using new.
    • The destructor ~Car() uses delete to free the memory allocated for brand when the object is destroyed.
    • If we didn’t implement the destructor, the memory allocated for brand would not be released, leading to a memory leak.

    Summary of Constructors and Destructors

    • Constructors are special functions used to initialize an object’s data members when the object is created. They can be default, parameterized, or copy constructors.
    • Destructors are special functions used to clean up resources when an object is destroyed. They are automatically invoked when an object goes out of scope or is explicitly deleted.
    • Constructors and destructors are key to resource management, ensuring that objects are correctly initialized and resources are cleaned up when they are no longer needed.

    Together, constructors and destructors allow for efficient and safe memory and resource management in object-oriented systems.

    ← Previous topic 4
    Data Encapsulation
    Next topic 6 →
    Access Modifiers

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.2kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Object Oriented Programming