Overloading + operator with classes containing array pointers (C++) - c++

I am currently writing a "Polynomial" class in order to practice Operator Overloading. I have successfully overloaded the stream extraction and insertion operators, but I am having some trouble with the "+" operator.
My class has a private pointer that proceeds to create an array in the constructor. I understand how one would overload the "+" operator with a complex number class, for example, but I'm getting confused with this program.
Guidance in finding a solution would be greatly appreciated.
Thank you.
#include<iostream>
#include<stdexcept>
using namespace std;
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
class Polynomial
{
friend istream& operator>>(istream& in, Polynomial& p);
friend ostream& operator<<(ostream& out, const Polynomial& p);
public:
Polynomial(int = 10);
~Polynomial();
void assignExponent();
Polynomial operator+(const Polynomial& other);
private:
int SIZE;
int *exponents;
int *polyPtr; //***************
};
#endif
//CONSTRUCTOR
Polynomial::Polynomial(int arraySize)
{
if(arraySize > 0)
SIZE = arraySize;
else
{
cout << "Array size must be greater than 0. Program will now "
<< "Terminate..." << endl;
system("pause");
exit(0);
}
polyPtr = new int[SIZE]; //*********************
exponents = new int[SIZE];
for(int i = 0; i<SIZE; i++)
polyPtr[i] = 0;
assignExponent();
};
//DESTRUCTOR
Polynomial::~Polynomial() //******************
{
delete [] polyPtr;
};
//STREAM INSERTION
istream& operator>>(istream& in, Polynomial& p)
{
for(int i = 0; i<p.SIZE; i++)
{
in >> p.polyPtr[i]; //*************
}
return in;
};
//STREAM EXTRACTION
ostream& operator<<(ostream& out, const Polynomial& p)
{
int exponent;
for(int i = 0; i<p.SIZE; i++)
{
exponent = (p.SIZE - 1) - i;
if(p.polyPtr[i] != 1)
{
if(exponent > 0 && exponent != 1)
out << p.polyPtr[i] << "x^" << exponent << " + ";
if(exponent == 1)
out << p.polyPtr[i] << "x" << " + ";
if(exponent == 0)
out << p.polyPtr[i];
}
//In order to not display coefficient if = 1
else
{
if(exponent > 0 && exponent != 1)
out << "x^" << exponent << " + ";
if(exponent == 1)
out << "x" << " + ";
if(exponent == 0)
out << p.polyPtr[i];
}
}
return out;
};
//Assigns a value for exponent
void Polynomial::assignExponent()
{
for(int i = 0; i<SIZE; i++)
{
exponents[i] = (SIZE - 1) - i;
}
};
//OVERLOAD OF + OPERATOR
Polynomial Polynomial::operator+(const Polynomial& other)
{
Polynomial sum(SIZE);
int difference;
//If the first polynomial is larger
if (SIZE > other.SIZE)
{
difference = SIZE - other.SIZE;
for(int i = 0; i<SIZE; i++)
{
if(i - difference < 0)
sum.polyPtr[i] = polyPtr[i];
else
{
sum.polyPtr[i] = polyPtr[i] +
other.polyPtr[i - difference];
}
}
}
//If the second polynomial is larger **PROBLEM**
if(other.SIZE > SIZE)
{
difference = other.SIZE - SIZE;
for(int i = 0; i<other.SIZE; i++)
{
if(i - difference < 0)
sum.polyPtr[i] = other.polyPtr[i];
else
{
sum.polyPtr[i] = other.polyPtr[i] +
polyPtr[i - difference];
}
}
}
//If the polynomials are equal
if(SIZE == other.SIZE)
{
for(int i = SIZE-1; i >= 0; i--)
{
sum.polyPtr[i] = polyPtr[i] + other.polyPtr[i];
}
}
return sum;
};
int main()
{
int polySize;
//User enters a size for the first & second polynomial
cout << "Enter a size for the first polynomial: ";
cin >> polySize;
Polynomial pOne(polySize);
cout << "\nEnter a size for the second polynomial: ";
cin >> polySize;
Polynomial pTwo(polySize);
//User enters in values (Overload of >> operator
cout << "\n\nEnter in values for the first polynomial, "
<< "in the format - (x x x x): " << endl;
cin >> pOne;
cout << "\nEnter in values for the second polynomial, "
<< "in the format - (x x x x): " << endl;
cin >> pTwo;
//Overload << operator for output
cout << "\nPolynomial 1 is: " << pOne << endl
<< "Polynomial 2 is: " << pTwo << endl;
Polynomial pThree = pOne + pTwo;
cout << "\nAfter being added together, the new polynomial is: "
<< pThree << endl;
system("pause");
}
I have updated my current code because I did not think opening another question would be the best way to go. Anyway, in trying to line up my polynomial's to be added, I've partially succeeded. The only problem that arises is when the second polynomial, pTwo, is larger than the first. I've labeled the section of code, PROBLEM. Thanks in advance.

I guess the + should write like below:
class Polynomial
{
// ...
Polynomial operator+(const Polynomial& other);
// ...
};
Polynomial Polynomial::operator+(const Polynomial& other)
{
Polynomial sum(SIZE);
for(int i = 0; i< SIZE; i++)
{
sum.polyPtr[i] = polyPtr[i] + other.polyPtr[i];
}
return sum;
}

Related

Error happens during deleting the dynamic allocated 2d array?

I am learning c++ and made my code of Matrix generating Class with operations.
However, When I try to delete the two matrices which input by user after the whole works, it pops up the message:
"Exception thrown at 0x0F4DBF9B (ucrtbased.dll) in Matrix 1.3.exe: 0xC0000005: Access violation reading location 0xDDDDDDCD"
at "(45)the delete[] arr[i];" line, which is in the destructor.
I tried to remove the brackets, but as I need those brackets to remove arrays, it also did not work.
Do you have any idea whats going wrong here?
#include <iostream>
#include <iomanip>
using namespace std;
class Matrix
{
private:
int row, col;
int** arr;
public:
Matrix(int, int);
~Matrix();
int getRow() const;
int getCol() const;
int** getMatrixArr() const;
friend Matrix* operator+(const Matrix&, const Matrix&);
friend Matrix* operator-(const Matrix&, const Matrix&);
friend Matrix* operator*(const Matrix&, const Matrix&);
friend Matrix* operator*(const Matrix&, int);
friend ostream& operator<<(ostream&, const Matrix*);
friend istream& operator>>(istream&, const Matrix&);
};
//construct and destruct--------------------------------------------------------------------------------------------------
Matrix::Matrix(int row, int col)
{
this->row = row;
this->col = col;
arr = new int*[row];
for (int i = 0; i < row; i++)
{
arr[i] = new int[col];
}
}
Matrix::~Matrix()
{
for (int i = 0; i < row; i++)
{
delete[] arr[i];
}
delete[] arr;
}
//getters------------------------------------------------------------------------------------------------------------------
int Matrix::getRow() const
{
return row;
}
int Matrix::getCol() const
{
return col;
}
int** Matrix::getMatrixArr() const
{
return arr;
}
//operation methods(OpOv)----------------------------------------------------------------------------------------------------------
Matrix* operator+(const Matrix& m, const Matrix& n)
{
Matrix* sum = new Matrix(m.row, m.col);
cout << "calculating..." << endl;
for (int i = 0; i <m.row; i++)
{
for (int j = 0; j <m.col; j++)
{
cout << setw(3) << m.arr[i][j] << "+" << n.arr[i][j];
sum->arr[i][j] = m.arr[i][j] + n.arr[i][j];
}
cout << endl;
}
return sum;
}
Matrix* operator-(const Matrix& m, const Matrix& n)
{
Matrix* sum = new Matrix(m.row, m.col);
cout << "caluclating..." << endl;
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < m.col; j++)
{
cout << setw(3) << m.arr[i][j] << "-" << n.arr[i][j];
sum->arr[i][j] = m.arr[i][j] - n.arr[i][j];
}
cout << endl;
}
return sum;
}
Matrix* operator*(const Matrix& m, const Matrix& n)
{
Matrix* sum = new Matrix(m.row, n.col);
cout << "calculating..." << endl;
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < n.col; j++)
{
sum->arr[i][j] = 0;
}
}
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < n.col; j++)
{
for (int t = 0; t < m.col; t++)
{
cout << setw(3) << "+" << m.arr[i][t] << "x" << n.arr[t][j];
sum->arr[i][j] += m.arr[i][t] * n.arr[t][j];
}
}
cout << endl;
}
return sum;
}
Matrix* operator*(const Matrix& m, int num)
{
Matrix* sum = new Matrix(m.row, m.col);
cout << "calculating..." << endl;
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < m.col; j++)
{
cout << setw(3) << m.arr[i][j] << "x" << num;
sum->arr[i][j] = m.arr[i][j] * num;
}
cout << endl;
}
return sum;
}
// input & output ---------------------------------------------------------------------------------------------------------------------
istream& operator>>(istream& is, const Matrix& m)
{
cout << "Enter the values for the Matrix (expecting: " << m.row * m.col << "): ";
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < m.col; j++)
{
is >> m.arr[i][j];
}
}
return is;
}
ostream& operator<<(ostream& os, const Matrix* m)
{
cout << "result: " << endl;
for (int i = 0; i < m->row; i++)
{
for (int j = 0; j < m->col; j++)
{
os << setw(3) << m->arr[i][j];
}
cout << endl;
}
return os;
}
//main-------------------------------------------------------------------------------------------------------------------------------------
int main()
{
int rowNum1, colNum1;
cout << "what is the row of the Matrix 1?: " << endl;
cin >> rowNum1;
cout << "What is the column for the Matrix 1?: " << endl;
cin >> colNum1;
Matrix m1(rowNum1, colNum1);
cin >> m1;
int rowNum2, colNum2;
cout << "what is the row of the Matrix 2?: " << endl;
cin >> rowNum2;
cout << "What is the column for the Matrix 2?: " << endl;
cin >> colNum2;
Matrix m2(rowNum2, colNum2);
cin >> m2;
int choice;
do
{
cout << "Now, what operation do you want to use?" << endl;
cout << "1) addition, 2) Sub action, 3)Multiplication, 4) scalar multiplication 5) quit" << endl << ":";
cin >> choice;
if (choice == 1)
{
if (m1.getRow() != m2.getRow() || m1.getCol() != m2.getCol())
{
cout << "The number of rows or columns of both Matrices are not same, you cannot add them together." << endl;
return 0;
}
else
{
Matrix * result = (m1 + m2);
cout << result << endl;
}
}
else if (choice == 2)
{
if (m1.getRow() != m2.getRow() || m1.getCol() != m2.getCol())
{
cout << "The number of rows or columns of both Matrices are not same, you cannot add them together." << endl;
return 0;
}
else
{
Matrix * result = (m1 - m2);
cout << result << endl;
}
}
else if (choice == 3)
{
if (m1.getCol() != m2.getRow())
{
cout << "Your first Matrix's number of columns and the second Matrice's number of rows are not accorded." << endl;
return 0;
}
else
{
Matrix* result = (m1 * m2);
cout << result << endl;
}
}
else if (choice == 4)
{
int value;
cout << "What is the integer value for the multiplication?: ";
cin >> value;
int MatCho;
cout << "First Matrix or Second Matrix(1 or 2)?: ";
cin >> MatCho;
if (MatCho == 1)
{
Matrix* result = (m1 * value);
cout << result << endl;
}
else if (MatCho == 2)
{
Matrix* result = (m2 * value);
cout << result << endl;
}
else
{
cout << "invalid input" << endl;
}
}
else if (choice == 5)
{
break;
}
else
{
cout << "Invalid input" << endl;
}
} while (choice != 5);
m1.~Matrix();
m2.~Matrix();
return 0;
}
Two issues here:
Never call destructor explicitly like you do with m1 and m2 here. Their destructors will be called automatically at the end of the main function in any case. So for you the destructors will run twice. On the second run, the array of pointers has already been deleted. But row, col and the pointer still has their old values and will try to access and delete already freed memory.
All your operations you do on the matrices will leak memory. You are using new inside the operator functions but never deleting the result. It is a bad habit expecting the user of a function to delete memory you have allocated. Return by value instead. This will actually not infer any performance loss, if you implement a move constructor (http://www.learncpp.com/cpp-tutorial/15-3-move-constructors-and-move-assignment/)
Remove the manual call to the destructors. As they're stack-allocated, the C++ compiler you use will handle them when you exit the main function, even if you already called them (which is what is happening).

Quick sort of dynamic massive of objects doesn't work correctly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
In my task I have to make class city, which have data members
width(GeografskaShirina)
lenght(GeografskaDaljina)
ime(name)
NadmorskaVisochina(height)
I have constructor by defalut,which input data, copy constructor and predefinition of operator = .
I should sort my dynamic array bulgaria by GeografskaDaljina(length), using quick sort, which I realized in method of class quicksort. I have also a Output() method(to print sorted names of cities), method getDaljina(),which returns GeografskaDaljina(length).
The problem is that when I call quicksort in main(), sorting doesn't work correctly and doesn't print wishing results.
#include "stdafx.h"
#include<string>
#include<iostream>
using namespace std;
class city {
private:
string ime;
double GeografskaShirina;
double GeografskaDaljina;
double NadmorskaVisochina;
public:
city();
double getDaljina();
string getN();
void Output();
city(const city& p);
city& operator = (const city& p);
void quicksort(city bulgaria[], int left, int right);
};
city::city(const city& p)
{
ime = p.ime;
GeografskaDaljina = p.GeografskaDaljina;
GeografskaShirina = p.GeografskaShirina;
NadmorskaVisochina = p.NadmorskaVisochina;
}
city& city::operator = (const city& p)
{
if (this != &p)
{
ime = p.ime;
GeografskaDaljina = p.GeografskaDaljina;
GeografskaShirina = p.GeografskaShirina;
NadmorskaVisochina = p.NadmorskaVisochina;
}
return *this;
}
city::city()
{
cout << "Vavedete ime grad: ";
cin >> ime;
cout << "Vavedete geografskata shirina na grada: ";
cin >> GeografskaShirina;
cout << "geografskata daljina na grada: ";
cin >> GeografskaDaljina;
cout << "Vavedete nadmorska visochina na grada: ";
cin >> NadmorskaVisochina;
cout << "---------------------------------" << endl;
}
void city:: quicksort(city bulgaria[], int left, int right)
{
int min;
min = (left + right) / 2;
cout << left << endl;
cout << right << endl;
int i = left;
int j = right;
int pivot = bulgaria[min].getDaljina();
while (left < j || i < right)
{
while (bulgaria[i].getDaljina() < pivot)
i++;
while (bulgaria[i].getDaljina()>pivot)
j--;
if (i <= j)
{
city temp = bulgaria[i];
bulgaria[i] = bulgaria[j];
bulgaria[j] = temp;
i++;
j--;
}
else
{
if (left < j)
{
quicksort(bulgaria, left, j);
}
if (i < right)
{
quicksort(bulgaria, i, right);
}
return;
}
}
return;
}
double city::getDaljina() {
return GeografskaDaljina;
}
string city::getN() {
return ime;
}
void city::Output()
{
cout << "Imeto e " << ime << endl;
cout << "Geografskata shirina e " << GeografskaShirina << endl;
cout << "Geografskata duljina e " << GeografskaDaljina << endl;
cout << "Nadmorskata visochina e " << NadmorskaVisochina << endl;
}
int main()
{
int n;
int i=0;
cout << "Broi gradove : ";
cin >> n;
cout << endl;
city *bulgaria = new city[n];
bulgaria[i].quicksort(bulgaria, 0,n-1);
for (int i = 0; i < n; i++)
{
bulgaria[i].Output();}
return 0;}
You use the wrong index in the second while loop in city::quicksort. You schold use j to compare the right value with the pivot value:
while (bulgaria[j].getDaljina()>pivot)
j--;

Issue with array index out of bounds assignment

I have seen several articles regarding something similar but none of them seem to help me. I would appreciate if someone could look at my code and tell me what I am doing wrong here. My teacher is not helping much. I commented out lines 65 - 75 in the driver because i couldn't get it to compile with these, will need help with this as well
ArrayDriver.cpp
#include <iostream>
#include "myArray.h"
using namespace std;
int main()
{
myArray<int> list1(5);
myArray<int> list2(5);
int i;
cout << "list1 : ";
for (i = 0 ; i < 5; i++)
cout << list1[i] <<" ";
cout << endl;
cout << "Enter 5 integers: ";
for (i = 0 ; i < 5; i++)
cin >> list1[i];
cout << endl;
cout << "After filling list1: ";
for (i = 0 ; i < 5; i++)
cout << list1[i] <<" ";
cout<< endl;
list2 = list1;
cout << "list2 : ";
for (i = 0 ; i < 5; i++)
cout << list2[i] <<" ";
cout<< endl;
cout << "Enter 3 elements: ";
for (i = 0; i < 3; i++)
cin >> list1[i];
cout << endl;
cout << "First three elements of list1: ";
for (i = 0; i < 3; i++)
cout << list1[i] << " ";
cout << endl;
myArray<int> list3(-2, 6);
cout << "list3: ";
for (i = -2 ; i < 6; i++)
cout << list3[i] <<" ";
cout<< endl;
list3[-2] = 7;
list3[4] = 8;
list3[0] = 54;
list3[2] = list3[4] + list3[-2];
cout << "list3: ";
for (i = -2 ; i < 6; i++)
cout << list3[i] <<" ";
cout<< endl;
/*
if (list1 == list2)
cout << " list 1 is equal to list2 " << endl;
else
cout << " list 1 is not equal to list2" << endl;
if (list1 != list2)
cout << " list 1 is not equal to list2 " << endl;
else
cout << " list 1 is equal to list2" << endl;
*/
//10% EXTRA CREDIT: UNCOMMENT CODE IF YOU'VE SUCCESSFULLY IMPLEMENTED THE FOLLOWING:
//cout << list1<< (list1 == list2 ? " is equal to" : " not equal to ") << list2 << endl;
//cout << list1<< (list1 != list2 ? " not equal to" : " is equal to ") << list2 << endl;
return 0;
}
myArray.h
#ifndef MYARRAY_H
#define MYARRAY_H
//#pragma once
#include <iostream>
//#include <assert.h>
//#include <iomanip>
//#include <string>
using namespace std;
template <class DataType>
class myArray
{
//overload for <<
//friend ostream& operator<<(ostream& out, myArray<DataType>& arr);
//overload for >>
friend istream& operator>>(istream& in, myArray<DataType>& arr);
public:
//myArray();
myArray(int size);
myArray(int start, int end);
//~myArray();
//overload []
DataType& operator[](int i);
//overload == operator
friend bool operator==(myArray<DataType> &arr1, myArray<DataType> &arr2);
//overload != operator
friend bool operator!=(myArray<DataType> &arr1, myArray<DataType> &arr2);
//overload = opertator
myArray<DataType> &operator=(const myArray<DataType> &rhs)
{
if (myDataType != NULL)
delete[]myDataType;
myDataType = new DataType[rhs.arraySize];
arraySize = rhs.arraySize;
for (int i = 0; i < arraySize; i++)
myDataType[i] = rhs.myDataType[i];
return *this;
}
//function
void SetNULL();
protected:
int startIndex;
int endIndex;
int arraySize;
//template
DataType *myDataType;
};
#endif
template <class DataType>
DataType& myArray<DataType>::operator[](int i)
{
if (i > arraySize)
{
cout << "Array out of bounds: " << endl;
}
else if (startIndex == 0)
{
return myDataType[i];
}
else
{
return myDataType[(startIndex + (i - 1))];
}
}
template <class DataType>
myArray<DataType>::myArray(int size) :
arraySize(size), startIndex(0), endIndex(size)
{
myDataType = new DataType[arraySize];
SetNULL();
}
template <class DataType>
myArray<DataType>::myArray(int start, int end) :
startIndex(start), endIndex(end)
{
if (start > end)
{
cout << "Invalid start position: " << endl;
}
else
{
arraySize = end - start;
}
myDataType = new DataType[arraySize];
SetNULL();
}
template <class DataType>
void myArray<DataType>::SetNULL()
{
for (int i = startIndex; i < endIndex; i++)
{
myDataType[i] = (DataType)0;
}
}
//overload == operator
template <class DataType>
bool operator==(myArray<DataType> &arr1, myArray<DataType> &arr2)
{
bool testBool = true;
for (int i = 0; i < arraySize; i++)
{
if (arr1[i] != arr2[i])
{
testBool = false;
}
}
return testBool;
}
//overload != operator
template <class DataType>
bool operator!=(myArray<DataType> &arr1, myArray<DataType> &arr2)
{
bool testBool = true;
for (int i = 0; i < arraySize; i++)
{
if (arr1[i] == arr2[i])
{
testBool = false;
}
}
return testBool;
}
//overload >> operator
template <class DataType>
istream& operator>> (istream &in, myArray<DataType> &aList)
{
for (int i = 0; i < aList.arraySize; i++)
in >> aList.list[i];
return in;
}
That's why not ignoring warnings (or using debugger) is helpful. My compiler showed the issue (via warnings), which should be the culprit of your problem.
In function:
myArray<DataType> &operator=(const myArray<DataType> &rhs)
{
if (myDataType = NULL)
delete[]myDataType;
myDataType = new DataType[rhs.arraySize];
arraySize = rhs.arraySize;
for (int i = 0; i < arraySize; i++)
myDataType[i] = rhs.arraySize;
return *this;
}
UPDATE: You are also assigning the array size as elements of your newly created copy. Copy actual elements.
UPDATE #2: As pointed out by fellow commenters, you also forgot to check for self-assignment. Check if the array pointer of your current array is equal to the one you are assigning.
you are doing an assignment instead of comparison in the first if statement. Consider doing this:
myArray<DataType> &operator=(const myArray<DataType> &rhs)
{
if (myDataType == rhs.myDataType) //CHECK IF THE ARRAY IS THE SAME (self-assignment case).
return *this;
// Missing '!' character here!!!
if (myDataType != NULL)
delete[]myDataType;
myDataType = new DataType[rhs.arraySize];
arraySize = rhs.arraySize;
for (int i = 0; i < arraySize; i++)
myDataType[i] = rhs.myDataType[i]; // COPY ACTUAL ELEMENTS INSTEAD OF WRITTING ARRAY SIZE.
return *this;
}
And, to avoid such issues in the future (if your compiler doesn't pick up on issues like this, consider doing comparisons, with constant values, like this:
if (NULL != myDataType)
delete[]myDataType;
And then your compiler will, no matter what, pick up on the issue, since it can't assign to a constant value.
UPDATE #3: Also, as I noticed, you are also allowing for arrays to have user defined start/end indexes. But, you would need to rethink your current approach of calculating the index at which to get the elements in such a case (where startIndex != 0). You are getting the position of element with formula: 'startIndex + (i - 1)'. But in your test case, in list3, where the range of indexes is [-2; 6), and you start your for loop, the initial index equates to -2 + (-2 - 1) = -2 - 3 = -5. I am not sure why your code isn't crashing here, but it should.
Also, to implement the comparisons operators, check if the size is the same at first, since if one of the arrays is smaller, and you are iterating through the indexes of the larger one, it should crash, when you will access the non-existing index (and to be honest, if sizes of arrays differ - they are not equal, are they?).

How to make public members of a class private?

I'm brand new to programming (in general) and C++ (in particular). I'm trying to take the following public member variables and make them private:
int *coeff;
int order;
Unfortunately, I'm seeing the following errors:
'Poly::coeff' : cannot access private member declared in class 'Poly'
and
'Poly::order' : cannot access private member declared in class 'Poly'
Here's my code:
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
using namespace std;
class Poly
{
public:
int *coeff;
int order;
int getData();
int display(int *coeff, int order);
void addition(Poly P1, Poly P2);
void subtraction (Poly P1, Poly P2);
void multiplication (Poly P1, Poly P2);
// ~Poly();
};
int Poly::display(int *coeff, int order)
{
int i;
int j;
for (i = order; i >= 0; i--)
{
cout << coeff[i] << "x^" << i;
if ((i - 1) != -1)
{
cout << "+";
}
}
cout << "\n";
return 0;
}
int Poly::getData()
{
int i;
cout << "Please enter the order of the polynomial: ";
cin >> order;
coeff = new int[order + 1];
for (i = order; i >= 0; i--)
{
cout << "Please enter the coefficient of x^" << i << " :";
cin >> coeff[i];
}
return 0;
}
void Poly::addition(Poly P1, Poly P2)
{
int max;
int i;
max = (P1.order > P2.order) ? P1.order : P2.order;
int *add = new int[max + 1];
if (P1.order == P2.order)
{
for (i = P1.order; i >= 0; i--)
{
add[i] = P1.coeff[i] + P2.coeff[i];
}
}
if (P1.order > P2.order)
{
for (i = P1.order; i > P2.order; i--)
{
add[i] = P1.coeff[i];
}
for (i = P2.order; i >= 0; i--)
{
add[i] = P1.coeff[i] + P2.coeff[i];
}
}
if (P1.order < P2.order)
{
for (i = P2.order; i > P1.order; i--)
{
add[i] = P2.coeff[i];
}
for (i = P1.order; i >= 0; i--)
{
add[i] = P1.coeff[i] + P2.coeff[i];
}
}
cout << "\nAddition:";
display(add, max);
cout << "\n";
}
void Poly::subtraction(Poly P1, Poly P2)
{
int max;
int i;
max = (P1.order > P2.order) ? P1.order : P2.order;
int *sub = new int[max + 1];
if (P1.order == P2.order)
{
for (i = P1.order; i >= 0; i--)
{
sub[i] = P1.coeff[i] - P2.coeff[i];
}
}
if (P1.order > P2.order)
{
for (i = P1.order; i > P2.order; i--)
{
sub[i] = P1.coeff[i];
}
for (i = P2.order; i >= 0; i--)
{
sub[i] = P1.coeff[i] - P2.coeff[i];
}
}
if (P1.order < P2.order)
{
for (i = P2.order; i > P1.order; i--)
{
sub[i] = -P2.coeff[i];
}
for (i = P1.order; i >= 0; i--)
{
sub[i] = P1.coeff[i] - P2.coeff[i];
}
}
cout << "\nSubtraction:";
display(sub, max);
cout << "\n";
}
void Poly::multiplication(Poly P1, Poly P2)
{
int i;
int j;
int max;
max = P1.order + P2.order;
int *mult = new int[max + 1];
for (i = P1.order; i >= 0; i--)
for (j = P2.order; j >= 0; j--)
{
mult[i + j] += P1.coeff[i] * P2.coeff[i];
}
cout << "\nMultiplication:";
display(mult, max);
}
int main()
{
int choice;
Poly P1, P2, P3;
cout << "-------- Instructions --------" << endl;
cout << "For polynomial 1... " << endl;
P1.getData();
cout << endl;
cout << "For polynomial 2... " << endl;
P2.getData();
while (1)
{
cout << "\n******** Menu Selection ********" << endl;
cout << "1: Addition\n2: Subtraction\n3: Mutiplication\n0: Exit" << endl;
cout << "Please enter your choice (1, 2, 3 or 0):";
cin >> choice;
switch (choice)
{
case 1:
cout << "\n-------- Addition --------\n";
cout << "Polynomial 1: ";
P1.display(P1.coeff, P1.order);
cout << "Polynomial 2: ";
P2.display(P2.coeff, P2.order);
P3.addition(P1, P2);
cout << "--------------------------\n";
break;
case 2:
cout << "\n------ Subtraction ------\n";
cout << "Polynomial 1: ";
P1.display(P1.coeff, P1.order);
cout << "Polynomial 2: ";
P2.display(P2.coeff, P2.order);
P3.subtraction(P1, P2);
cout << "--------------------------\n";
break;
case 3:
cout << "\n------ Subtraction ------\n";
cout << "Polynomial 1: ";
P1.display(P1.coeff, P1.order);
cout << "Polynomial 2: ";
P2.display(P2.coeff, P2.order);
P3.multiplication(P1, P2);
cout << "--------------------------\n";
break;
case 0:
cout << "The program will now terminate. Thank you." << endl;
exit(0);
default:
cout << endl;
cout << "You have entered an invalid selection." << endl;
cout << "Please enter a positive integer between 0 and 3.";
cout << endl;
}
}
return 0;
}
Can anyone offer guidance on how to best modify my code so that int *coeff and int order are private members?
Thanks very much in advance.
-Ryan
The idea of making something private means you're not allowed to access outside of member or friend functions (that's the purpose of private). The code is failing in main at things like P1.display(P1.coeff, P1.order) because main isn't a member of the Poly class and, as such, is not allowed to access Poly::coeff or Poly::order (as the compiler is telling you).
I would suggest you change the definition of Poly::display(int *coeff, int order) to not require you pass in coeff and order, since the instance already knows what these values are. I would also take out the return 0, since it isn't buying you anything.
void Poly::display()
{
int i;
int j;
for (i = order; i >= 0; i--)
{
cout << coeff[i] << "x^" << i;
if ((i - 1) != -1)
{
cout << "+";
}
}
cout << "\n";
}
Inside that member function, the variables order and coeff are implicitly picking up the members of your class that were previously shadowed by the parameters you were passing.
"Can anyone offer guidance on how to best modify my code so that int *coeff and int order are private members?"
Your code in main()
P1.display(P1.coeff, P1.order);
still tries to access these now private class members directly, which won't work of course (that's why we make these members private).
For your case, you don't need to pass these variables as parameters to that function at all, since the actual values are available for the P1 instance of class Poly already.
Change your member function signature to
int display();
and definition to
int Poly::display() {
int i;
int j;
for (i = order; i >= 0; i--) {
cout << coeff[i] << "x^" << i;
if ((i - 1) != -1) {
cout << "+";
}
}
cout << "\n";
return 0;
}
Note that accessing order or coeff inside the Poly::display() member function, can be read as equivalent to this->order and this->coeff.
Class member functions can be considered to have a this pointer implicitly, and can access (private) class member variables directly, without need to specify these as parameters.
After changing the stuff as proposed above, you can just call
P1.display();
Change other signatures/access to coeff, order analogous.
NOTE:
There are more flaws in your class declarations. Something like
void addition(Poly P1, Poly P2);
won't work well. You want to operate with the actual instance as the left hand value, and the other as a constant right hand value. IMHO your member function should look like this
Poly& addition(const Poly& rhs) {
// perform addition operations with this and rhs
return *this;
}
Poly addition(const Poly& rhs) const {
Poly result = *this;
// perform addition operations with result and rhs
return result;
}

Overloading Extraction and Insertion Operators C++

Hello i've overloaded the insertion and Extraction operators. when i run my program the Insertion does not seem to output the values although the Extraction is putting the values into the class.
Its seems like the insertions view of the instance has no values in it.
Main
/ Input Poly
cout << "Input p1: " << endl;
Polynomial P1;
cin >> P1;
// Output Poly
cout << "p1(x) = " << P1 << '\n' << endl;
Class function
//Insertion
ostream& operator<<(ostream& os, Polynomial Poly){
for (int i=0; i < Poly.polyNum; i++) {
os << Poly.poly[i] << " x^" << i;
if(i != Poly.polyNum - 1){
os << " + ";
}
}
return os;
}
//Extraction
istream& operator>>(istream& is, Polynomial Poly){
int numP = 0;
int * tempP;
is >> numP;
tempP = new int [numP+1];
for (int i=0; i < numP; i++) {
is >> tempP[i];
}
Poly.polyNum = numP;
Poly.poly = new int[Poly.polyNum +1];
for (int i=0; i < Poly.polyNum; i++) {
Poly.poly[i] = tempP[i];
}
return is;
}
istream& operator>>(istream& is, Polynomial Poly)
should be
istream& operator>>(istream& is, Polynomial& Poly)
What you're doing now is simply changing the members of a copy of your object:
Polynomial P1;
cin >> P1;
P1 is not modified after this.