What are constructor and destructor? Explain copy and parameterized constructor With an example

SOLUTION....

✨ Constructor and Destructor in C++

📌 Constructor

  • A constructor is a special member function of a class that is automatically called when an object is created.

  • It has the same name as the class and no return type.

  • Its purpose is to initialize data members.

📌 Destructor

  • A destructor is a special member function that is automatically invoked when an object goes out of scope or is deleted.

  • It has the same name as the class but is preceded by a ~ (tilde).

  • Used to release resources like memory or files.

📌 Types of Constructors

  1. Parameterized Constructor

    • A constructor that takes arguments to initialize objects with specific values.

    Example:


class Student {
    int roll;
    string name;
public:
    Student(int r, string n) {   // Parameterized constructor
        roll = r;
        name = n;
    }
    void show() {
        cout << roll << " - " << name << endl;
    }
};

OUTPUT

Copy Constructor

  • A constructor that initializes an object by copying data from another object.

  • Syntax: ClassName(const ClassName &obj)

Example:


class Student {
    int roll;
    string name;
public:
    Student(int r, string n) {   // Parameterized constructor
        roll = r;
        name = n;
    }
    Student(const Student &s) {   // Copy constructor
        roll = s.roll;
        name = s.name;
    }
    void show() {
        cout << roll << " - " << name << endl;
    }
};

Output

📌 Summary

  • Constructor → Initializes objects (can be default, parameterized, or copy).

  • Destructor → Cleans up resources when object is destroyed.

  • Parameterized constructor → Allows initializing objects with specific values.

  • Copy constructor → Creates a new object as a copy of an existing one.

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.