Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Sunday, September 29, 2024

Constructors and Destructors in C++

 In C++, constructors and destructors are special member functions that are automatically invoked when an object is created and destroyed, respectively. They play a crucial role in object-oriented programming for initializing and cleaning up resources.

1. Constructor

A constructor is a special type of member function that is called automatically when an object of a class is instantiated. Its primary purpose is to initialize the object's members. A constructor has the same name as the class and does not have a return type.

Types of Constructors:

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Dynamic Constructor

1. Default Constructor

A default constructor is a constructor that takes no arguments. If no constructor is provided in the class, C++ provides a default constructor automatically.

Example:

#include <iostream>

using namespace std;

class MyClass {

public:

    MyClass() {  // Default constructor

        cout << "Default constructor called!" << endl;

    }

};

int main() {

    MyClass obj;  // Default constructor is called

    return 0;

}



2. Parameterized Constructor

A parameterized constructor is one that accepts arguments to initialize the object with specific values.

Example:

#include <iostream>

using namespace std;

class MyClass {

private:

    int x;

public:

    MyClass(int val) {  // Parameterized constructor

        x = val;

        cout << "Parameterized constructor called! x = " << x << endl;

    }

};

int main() {

    MyClass obj(10);  // Parameterized constructor is called with argument 10

    return 0;

}



3. Copy Constructor

A copy constructor is 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 an argument.

Example:

#include <iostream>

using namespace std;

class MyClass {

private:

    int x;

public:

    MyClass(int val) {  // Parameterized constructor

        x = val;

    }

    MyClass(const MyClass &obj) {  // Copy constructor

        x = obj.x;

        cout << "Copy constructor called! x = " << x << endl;

    }

};

int main() {

    MyClass obj1(20);      // Parameterized constructor is called

    MyClass obj2 = obj1;   // Copy constructor is called

    return 0;

}



4. Dynamic Constructor

A dynamic constructor allocates memory dynamically during object creation using pointers or dynamic memory allocation functions like new.

Example:

#include <iostream>

using namespace std;

class MyClass {

private:

    int *ptr;

public:

    MyClass(int val) {  // Dynamic constructor

        ptr = new int;  // Dynamically allocate memory

        *ptr = val;

        cout << "Dynamic constructor called! Value = " << *ptr << endl;

    }

    ~MyClass() {  // Destructor to deallocate memory

        delete ptr;

        cout << "Memory deallocated!" << endl;

    }

};

int main() {

    MyClass obj(30);  // Dynamic constructor is called

    return 0;

}


Constructor Overloading in C++ is a concept that allows a class to have more than one constructor with different parameter lists. This is similar to function overloading, where multiple functions can have the same name but different arguments. When an object is created, the appropriate constructor is chosen based on the number and type of arguments passed.

Key Points of Constructor Overloading:

  • Constructors must differ in the number or type of parameters.
  • The compiler automatically selects the appropriate constructor based on the arguments passed.
  • This is useful for providing multiple ways of initializing an object.

Example of Constructor Overloading

#include <iostream>
using namespace std;

class MyClass {
private:
    int x, y;

public:
    // Default constructor (no parameters)
    MyClass() {
        x = 0;
        y = 0;
        cout << "Default constructor called!" << endl;
        cout << "x = " << x << ", y = " << y << endl;
    }

    // Parameterized constructor (one parameter)
    MyClass(int a) {
        x = a;
        y = 0;
        cout << "Constructor with one parameter called!" << endl;
        cout << "x = " << x << ", y = " << y << endl;
    }

    // Parameterized constructor (two parameters)
    MyClass(int a, int b) {
        x = a;
        y = b;
        cout << "Constructor with two parameters called!" << endl;
        cout << "x = " << x << ", y = " << y << endl;
    }
};

int main() {
    MyClass obj1;       // Calls default constructor
    MyClass obj2(10);   // Calls constructor with one parameter
    MyClass obj3(20, 30); // Calls constructor with two parameters

    return 0;
}

Explanation:

  • MyClass obj1; – Calls the default constructor. Since no arguments are passed, the constructor with no parameters is invoked, setting both x and y to 0.

  • MyClass obj2(10); – Calls the constructor with one parameter. The value of x is set to 10, and y is set to 0 by default.

  • MyClass obj3(20, 30); – Calls the constructor with two parameters. Both x and y are initialized with the values 20 and 30, respectively.

2. Destructor

A destructor is a special member function that is automatically invoked when an object goes out of scope or is explicitly deleted. Its primary purpose is to release resources allocated to the object (like memory or file handles). It has the same name as the class, preceded by a tilde (~), and does not take arguments or return a value.

Example:

#include <iostream>
using namespace std;

class MyClass {
public:
    MyClass() {
        cout << "Constructor called!" << endl;
    }
    
    ~MyClass() {  // Destructor
        cout << "Destructor called!" << endl;
    }
};

int main() {
    MyClass obj;  // Constructor is called
    // When the scope ends, destructor is automatically called
    return 0;
}

Types of Destructors:

  1. Default Destructor: Automatically provided by the compiler if no destructor is defined.
  2. Custom Destructor: Defined by the programmer to release resources manually, especially in cases where dynamic memory is allocated.

Key Differences Between Constructor and Destructor:

  1. Constructor: Initializes an object, automatically called when an object is created.
  2. Destructor: Cleans up resources, automatically called when an object is destroyed.

Summary:

  • Constructors:
    • Default Constructor: No arguments, initializes objects with default values.
    • Parameterized Constructor: Takes arguments, initializes objects with specific values.
    • Copy Constructor: Creates a new object as a copy of an existing object.
    • Dynamic Constructor: Allocates memory dynamically during object creation.
  • Destructor: Cleans up resources when the object goes out of scope or is deleted.

Understanding constructors and destructors helps in managing memory and resources effectively, especially in object-oriented programming.

No comments:

Post a Comment