ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Constructors and Destructors
    Object Oriented ProgrammingTopic 5 of 24

    Constructors and Destructors

    7 minread
    1,244words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,244
      Code examples0
      DifficultyIntermediate