Constructor and destructor in C++ example program

Let's talk about constructors, a special part of a class that gets things going when you create an object. Here are the key points:

  1. What's a Constructor?

    • A constructor is like a helper function inside a class.
    • It shares the same name as the class itself.
    • It doesn't hand back any values.
    • Whenever you make a new object, the constructor jumps into action.
  2. Different Kinds of Constructors:

    • Parameterized Constructor: Takes some values when creating an object.
    • Copy Constructor: Makes a new object just like an existing one.
    • Default Constructor: The basic one that doesn't need any specific values.
  3. Destructor - The Cleanup Crew:

    • Destructors step in when it's time to free up memory.
    • They come into play when an object says its goodbyes.
    • No arguments, no return type, just a farewell to memory.

Now, let's dive into a couple of examples to make it more human-friendly:

Example: Parameterized Constructor and Destructor

#include<iostream>
using namespace std;

class MathOperation {
    int num1, num2;
public:
    // Parameterized constructor - sets initial values
    MathOperation(int x, int y) {
        num1 = x;
        num2 = y;
    }

    // Destructor - says goodbye and frees up memory
    ~MathOperation() {
        cout << "Cleaning up memory\n";
    }

    int add() {
        return (num1 + num2);
    }
};

int main() {
    // Creating an object with a parameterized constructor
    MathOperation obj(3, 4);

    // Performing addition using the 'add' method
    cout << "Sum: " << obj.add() << "\n";

    // Destructor automatically called when the object goes out of scope
    return 0;
}

Example: Default Constructor

#include<iostream>
using namespace std;

class Subtraction {
public:
    int operand1, operand2;

    // Default constructor - no specific values needed
    Subtraction() {
    }

    int subtract() {
        return (operand1 - operand2);
    }
};

int main() {
    // Creating an object with the default constructor
    Subtraction subtractionObj;

    // Setting values and performing subtraction
    subtractionObj.operand1 = 5;
    subtractionObj.operand2 = 9;
    cout << "Subtraction: " << subtractionObj.subtract();

    return 0;
}

Hope this makes the world of constructors and destructors a bit more relatable!

Next Post Previous Post
No Comment
Add Comment
comment url