SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Inheritance
Exercise:
Self-test Exercises
Question:9 | ISBN:9780321531346 | Edition: 7

Question

Give the definitions for the member function add_value, the copy constructor,

the overloaded assignment operator, and the destructor for the

following class. This class is intended to be a class for a partially filled

array. The member variable number_used contains the number of array

positions currently filled. The other constructor definition is given to help

you get started.

#include <iostream>

#include <cstdlib>

using namespace std;

class PartFilledArray

{

public:

PartFilledArray(int array_size);

PartFilledArray(const PartFilledArray& object);

~PartFilledArray();

void operator = (const PartFilledArray& right_side);

void add_value(double new_entry);

//There would probably be more member functions

//but they are irrelevant to this exercise.

protected:

double *a;

int max_number;

int number_used;

};

PartFilledArray::PartFilledArray(int array_size)

: max_number(array_size), number_used(0)

{

a = new double[max_number];

}

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

void PartFilledArray::add_value(double new_entry)

{

if (number_used == max_number)

{

cout << "Adding to a full array.\n";

exit(1);

}

else

{

a[number_used] = new_entry;

number_used++;

}

}

PartFilledArray::PartFilledArray

(const PartFilledArray& object)

: max_number(object.max_number),

number_used(object.number_used)

{

a = new double[max_number];

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

a[i] = object.a[i];

}

void PartFilledArray::operator =

(const PartFilledArray& right_side)

{

if (right_side.max_number > max_number)

{

delete [] a;

max_number = right_side.max_number;

a = new double[max_number];

}

number_used = right_side.number_used;

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

a[i] = right_side.a[i];

}

PartFilledArray::~PartFilledArray()

{

deletet[] a;

}

0 0

Discussions

Post the discussion to improve the above solution.