This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Friday, February 17, 2023

what are the roles of constructor and destructor? write a program to demonstrate parameterized and copy constructor.

 Constructors and destructors are special member functions in C++ classes that have specific roles:

  1. Constructors: To initialize objects of a class when they are created. They ensure that objects are properly initialized with default or user-defined values, so that they are ready for use.
  2. Destructors: To deallocate memory and release resources when an object of a class is destroyed. They ensure that objects are properly cleaned up and memory is freed, to prevent memory leaks and other related issues.

Here is an example program that demonstrates a parameterized constructor and a copy constructor:

#include <iostream>
#include <string>

using namespace std;

class MyClass {
private:
    int value;
    string name;

public:
    // parameterized constructor
    MyClass(int v, string n) {
        value = v;
        name = n;
        cout << "Parameterized constructor called for " << name << endl;
    }

    // copy constructor
    MyClass(const MyClass& obj) {
        value = obj.value;
        name = obj.name + " (copy)";
        cout << "Copy constructor called for " << name << endl;
    }

    ~MyClass() {
        cout << "Destructor called for " << name << endl;
    }

    void display() {
        cout << "Name: " << name << endl;
        cout << "Value: " << value << endl;
    }
};

int main() {
    // create an object using parameterized constructor
    MyClass obj1(10, "Object 1");
    obj1.display();

    // create a copy of the object using copy constructor
    MyClass obj2 = obj1;
    obj2.display();

    return 0;
}

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget