Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Take the code from below and add a copy constructor, a destructor and overload t

ID: 3554439 • Letter: T

Question

Take the code from below and add a copy constructor, a destructor and overload the assignment operator.

// if you examine the output from the code below, you can appreciate
// how it is important to define the copy constructor, overload
// the assignment operator and include a destructor


#include <iostream>
using namespace std;

class MyDynamicClass
{
public:
MyDynamicClass()
{
numP = new int[10];
count = 10;
}
MyDynamicClass(int cnt)
{
if (cnt > 1)
count = cnt;
else
count = 10;
numP = new int[count];
}
void set(int value)
{
for (int i=0; i<count; i++)
numP[i] = value;
}
void show()
{
for (int i=0; i<count; i++)
cout << numP[i] << ' ';
cout << endl;
}
private:
int *numP, count;
};

int main()
{
MyDynamicClass mdc1, mdc2(8);
mdc1.set(11);
mdc2.set(22);
mdc1.show();
mdc2.show();
mdc1 = mdc2; // assignment operator
mdc1.set(81);
MyDynamicClass mdc3(mdc2); // copy constructor
mdc2.set(82);
mdc3.show();
mdc1.show();
mdc2.show();
return 0;
}

Explanation / Answer

( Short, Simple & Verified )

#include<iostream>

using namespace std;

class MyDynamicClass

{

public:

    MyDynamicClass()

    {

        numP = new int[10];

        count = 10;

    }

    MyDynamicClass(int cnt)

    {

        if(cnt > 1) count = cnt;

        else count = 10;

        numP = new int[count];

    }

    // Copy Constructor

    MyDynamicClass(const MyDynamicClass & mdc)

    {

        this->numP = mdc.numP;

        this->count = mdc.count;

    }

    // Overloaded assignment operator

    MyDynamicClass & operator=(const MyDynamicClass & mdc)

    {

        this->numP = mdc.numP;

        this->count = mdc.count;

        return *this;

    }

    // Destructor

    ~MyDynamicClass()

    {

                delete[] this->numP;

    }

    void set(int value)

    {

        for(int i=0; i<count; i++)

            numP[i] = value;

    }

    void show()

    {

        for (int i=0; i<count; i++)

            cout << numP[i] << ' ';

        cout << endl;

    }

private:

    int *numP, count;

};

int main()

{

    MyDynamicClass mdc1, mdc2(8);

    mdc1.set(11);

    mdc2.set(22);

    mdc1.show();

    mdc2.show();

    mdc1 = mdc2; // assignment operator

    mdc1.set(81);

    MyDynamicClass mdc3(mdc2); // copy constructor

    mdc2.set(82);

    mdc3.show();

    mdc1.show();

    mdc2.show();

    return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote