C++ Polynomial Class, pointer array issue - c++

I have to write a program using this exact .h file not modifying anything. It must overload a few operators and be able to add polynomials.
Here is the .h file.
#ifndef H_polyClass
#define H_polyClass
#include <iostream>
using namespace std;
class polyClass
{
friend ostream& operator << (ostream&, const polyClass&);
//Overload the extraction operator
//Output format example: 5x^2 - 3x + 6
public:
void setPoly ( int myArray [], int myterms);
//Function to set the polynomial according to the parameter.
//Postcondition: polyArray = myArray; terms = myterms;
polyClass ( int myArray [], int myterms);
//Constructor
//Initializes the polynomial according to the parameter.
//Postcondition: polyArray = myArray; terms = myterms;
polyClass ();
//Default Constructor
//Initializes the polynomial.
//Postcondition: polyArray = NULL; terms = 0;
polyClass operator+ (const polyClass& otherPoly) const;
//overload the operator +
bool operator == (const polyClass& otherPoly) const;
//overload the operator ==
private:
int *polyArray; //pointer to an array that holds the term coefficients.
int terms; //the number of terms in the polynomial
};
#endif
Here is the .cpp file.
#include <iostream>
#include "polyClass.h"
using namespace std;
ostream &operator<<(ostream &out, const polyClass &poly)
{
out << poly.polyArray[1];
if(poly.terms > 1)
out << poly.polyArray[2];
if(poly.terms > 2){
for(int i = 2; i < poly.terms; i++){
out << poly.polyArray[i] << "x^" << i;
}
}
return out;
}
void polyClass::setPoly(int myArray[], int myterms)
{
for(int i = 0; i < myterms; i++)
polyArray[i] = myArray[i];
terms = myterms;
}
polyClass::polyClass(int myArray[], int myterms)
{
for(int i = 0; i < myterms; i++)
polyArray[i] = myArray[i];
terms = myterms;
}
polyClass::polyClass()
{
polyArray = NULL;
terms = 0;
}
polyClass polyClass::operator+(const polyClass &otherPoly) const
{
int size;
if(this->terms >= otherPoly.terms)
size = this->terms;
else
size = otherPoly.terms;
int *newArray = new int[size];
for(int i = 0; i < size; i++)
newArray[i] = otherPoly.polyArray[i] + this->polyArray[i];
return polyClass(newArray, size);
}
bool polyClass::operator==(const polyClass &otherPoly) const
{
if(otherPoly.terms != this->terms){
return false;
}
else if(otherPoly.terms == this->terms){
for(int i = 0; i < otherPoly.terms; i++){
if(polyArray[i] == this->polyArray[i])
return true;
}
}
else{
return false;
}
}
And so far this is my test.cpp file.
#include <iostream>
#include "polyClass.h"
using namespace std;
int main()
{
int myarray[] = {2,4,5};
int myarray2[] = {2,4,5};
int myarray3[] = {2,4};
polyClass p1(myarray, 3);
polyClass p2(myarray2, 3);
polyClass p3(myarray3, 2);
cout << "PolyClass p1 is : " << p1 << endl;
return 0;
}
The only error I'm getting using g++ is segmentation fault. I'm sure I have messed up some pointer array but I'm not sure. There is probably a few issues.

You never allocate memory for your int*.
polyClass::polyClass(int myArray[], int myterms)
{
for(int i = 0; i < myterms; i++)
polyArray[i] = myArray[i];
terms = myterms;
}
polyArray is not initialized here, but you try to access its elements.
Allocate memory for it first:
polyClass::polyClass(int myArray[], int myterms)
{
polyArray = new int[myterms]; //allocate memory here
for(int i = 0; i < myterms; i++)
polyArray[i] = myArray[i];
terms = myterms;
}

Related

Problem with printing copy constructor OOP

Having trouble with the printing copy constructors elements from Arr s to Arr s1 , also having troubles with << operator it doesn't work, please help cuz I am not pro just a student.
#include <iostream>
using namespace std;
class Arr {
private:
int size;
int *arr;
public:
Arr(int size,int *arr) {
this->size = size;
this->arr = new int [size];
for (int i = 0; i < size ; ++i) {
this->arr[i] = arr[i];
}
}
~Arr() {
delete[] arr;
}
Arr(const Arr &x) {
this->size = x.size;
this->arr = new int[x.size];
for (int i = 0; i < x.size; ++i) {
this->arr = x.arr;
}
}
Arr() : size(0),arr(0) {}
Arr(Arr &&x) {
this->size = x.size;
this->arr = new int[x.size];
for (int i = 0; i < x.size; ++i) {
this->arr = x.arr;
}
}
friend ostream &operator<<(ostream &out, const Arr &t) {
out << t.size;
for (int i = 0; i < t.size; i++) {
out << t.arr[i];
}
return out;
}
friend istream &operator>>(istream &in, Arr &t) {
in >> t.size;
for (int i = 0; i < t.size; ++i) {
in >> t.arr[i];
}
return in;
}
};
int main() {
int size = 3;
int arr [] = {1,2,3};
Arr s1(size,arr);
cin << s1;
cout<<s1;
Arr s(s1);
cout<<s; // not working at all
return 0;
}
You are writing
this->arr = x.arr;
in the copy constructor, rather than
this->arr[i] = x.arr[i];
That is, currently your code is copying the array pointer, not the elements of the array.
When you're debugging, first look over your code to make sure each part is doing what you want it to do and that you didn't make a typo like this. Then, if you don't find the problem, you can use a debugger like gdb to step through your code and monitor the values of the variables to make sure your program is doing what you'd like.

Overloading operator[] changing value

I'm trying to overload an int array, so basically if I have this in my main func
IntArray arr(10);
for(int i = 0; 0 < 10; i++)
a[i] = i * 10;
I was able to get
a[0] = 0, a[1] =10, a[2]=20.... so on
I was able to make this one work.
If I then do
IntArray arr(-3, 10)
with same for loop, I was able to get the appropriate answer as well.
BUT...
If I do
IntArray arr(6, 8)`
using same for loop I get c[6] = 1, c[7]=1, c[8] =0
I been trying to figure this out since yesterday, here's my code:
//---------------------Header file
#ifndef INTARRAY_H_
#define INTARRAY_H_
#include <iostream>
using namespace std;
class IntArray
{
private:
int first;
int last;
int size;
string arrName;
int* arrPtr;
public:
IntArray();
int& operator[](int i);
IntArray(int num);
IntArray(int num1, int num2);
int low();
int high();
void setName(string str);
//streams
friend istream& operator>>(istream& is, IntArray& d);
friend ostream& operator<<(ostream& os, IntArray& d);
};
#endif /* INTARRAY_H_ */
//---------------------
My int array class:
#include "IntArray.h"
IntArray::IntArray(){
size = 10;
first = 0; last = 9;
arrPtr = new int[size];
}
IntArray::IntArray(int num){
size = num;
first = 0; last = size-1;
arrPtr = new int[size];
//cout<<"\n the size "<<size<<endl;
//arrPtr[3] = 123;
//ex = 3;
}
IntArray::IntArray(int num1, int num2){
first = num1; last = num2;
size = last - first + 1;
//cout<<"\n the size "<<size<<endl;
arrPtr = new int[size];
}
int& IntArray::operator[](int i) {
if (i >= (last+1)){
cout<<"Error: Index out of range"<<endl;
exit(1);
}
return arrPtr[i];
}
int IntArray::getInt(int i){
return arrPtr[i];
}
//======================
int IntArray::low(){
return first;
}
int IntArray::high(){
return last;
}
//======================
//==========OUT stream==========
// for cout << justName<< endl;
ostream& operator<<(ostream& os, IntArray& aPtr) {
for(int i = aPtr.low(); i <= aPtr.high(); i++){
os << aPtr.arrName <<"[" << i << "] = " << aPtr[i] << " ";
}
return os;
}
void IntArray::setName(string str){
arrName = str;
}
For some apparent reason, after using my setName function on this test function, it changes the value to c[6] = 1, c[7]=1, c[8] =0.
void test3() {
IntArray c(6, 8);
for(int i = c.low(); i <= c.high(); i++)
c[i] = i * 10;
c.setName("c");
cout << c << endl;
}
Let me make this one clear. Like I said, I did narrowed down my problem.
IntArray a(10) //THIS ONE WORKS!
IntArray a(-3, 6) //THIS ONE WORKS!
IntArray a(6,8) //NOT working.
For the last one, the array outputs the right value, until I use the setName function.
This may not be your only problem but it looks like you want to allow users of your class to use the old Perl $[
To support this you'll need to modify it in your operator[]:
int& IntArray::operator[](int i) {
if (i > last || i < first ){
cout<<"Error: Index out of range"<<endl;
exit(1);
}
return arrPtr[i - first];
}
In the subscript operator you also should check that i is not less than first.
Tale into account that relative to the pointer you have to use indices starting from zero. So instead of
return arrPtr[i];
you have to write
return arrPtr[i - first];
Also it would be better if constructor
IntArray(int num);
would be declared like
IntArray( size_t num);
and correspondingly data member size would have type size_t

Why is this giving me an access violation? (C++)

I'm building a vector class for my data structures class, and I can't figure out why this is throwing an exception. Here's the complete Vector.h file:
#include <iostream>
using namespace std;
template <class T>
class Vector {
private:
// not yet implemented
Vector(const Vector& v);
Vector& operator=(const Vector& v);
T * Tarray;
int arraySize;
int currentSize;
public:
Vector() {
arraySize = 2;
currentSize = 0;
Tarray = new T[arraySize];
};
~Vector() {
delete[] Tarray;
};
void push_back(const T &e) {
++currentSize;
if (currentSize > arraySize) {
arraySize *= 4;
T * temp = new T[arraySize];
for (int i = 0; i < currentSize; i++) {
temp[i] = Tarray[i];
}
delete[] Tarray;
Tarray = new T[arraySize];
for (int j = 0; j < currentSize; j++) {
Tarray[j] = temp[j];
}
delete[] temp;
Tarray[currentSize - 1] = e;
}
else {
Tarray[currentSize - 1] = e;
}
};
void print() {
for (int i = 0; i < currentSize; i++) {
cout << Tarray[i] << " ";
}
};
int getCurrentSize() {
return currentSize;
};
int getArraySize() {
return arraySize;
};
// Not yet implemented
void pop_back();
int size() const;
T& operator[](int n);
};
And here's my complete main.cpp I was using to test it.
#include "Vector.h"
#include <iostream>
#include <string>
using namespace std;
int main() {
char c;
string * temp = new string[8];
Vector<string> newVector;
for (int i = 0; i < 8; i++) {
newVector.push_back("Hello world");
newVector.push_back("Hello world");
}
newVector.print();
cout << endl << "Current Size: " << newVector.getCurrentSize();
cout << endl << "Array Size: " << newVector.getArraySize();
cin >> c;
}
I would rewrite push_back as follows:
void push_back(const T &e) {
if (currentSize+1 > arraySize) {
arraySize *= 4;
T * temp = new T[arraySize];
for (int i = 0; i < currentSize; i++) {
temp[i] = Tarray[i];
}
delete[] Tarray;
Tarray = temp;
}
Tarray[currentSize] = e;
++currentSize;
};
Changes are:
Don't update currentSize until after you have copied the contents (thus not going out of bounds in Tarray).
Don't allocate and copy twice. Just assign Tarray to temp after deleting it.
Only stick element into Tarray in one place.
Update currentSize after, to avoid having to do -1 (It does require a single +1 in the first if instead.

Invalid allocation runtime error

I have to replicate a vector class using an int and overload a bunch of operators. How ever every time I try to use the +, -, or / operator I get a runtime error which says invalid allocation size: 4294967295 bytes. Any feed back on how I can improve my code is welcome as well.
my code:
myArray.h
#include<iostream>
using namespace std;
class myArray{
private:
int *A;
int lenght;
int maxSize;
public:
myArray(){lenght = 0; maxSize = 0; A = new int[maxSize];}
myArray(int s){maxSize = s; lenght = 0; A = new int[maxSize];}
myArray(const myArray &M);
~myArray(){delete[] A;}
const int getMaxSize(){return maxSize;}
const int getLenght(){return lenght;}
const myArray& operator +(const myArray& A);
const myArray& operator -(const myArray A);
const int operator *(const myArray& A);
const myArray& operator /(const myArray A);
const myArray& operator +(int A);
const myArray& operator -(int A);
const int operator *(int A);
const myArray operator /(int A);
const myArray operator ++();
const myArray operator ++(int);
const myArray operator --();
const myArray operator --(int);
myArray operator -();
int operator [](int ind) const;
myArray& operator =(const myArray& rho);
void push(int n);
int pop();
void insert(int n, int pos);
int remove(int pos);
void resize(int newSize);
};
myException.h
#include<iostream>
#include<exception>
#include<string>
using namespace std;
class myException: public exception
{
private:
int code;
string reason;
public:
myException(){code = 0; reason = "Unknown";}
myException(int c, string r){code = c; reason = r;}
friend ostream& operator <<(ostream& outputStream, const myException A);
};
ostream& operator <<(ostream& outputStream, const myException A)
{
outputStream << "Code: " << A.code << " Reason: " << A.reason << endl;
return outputStream;
}
myArray.cpp
#ifndef MYARRAY_H
#define MYARRAY_H
#include "myArray.h"
#include "myException.h"
//Copy contructor
myArray::myArray(const myArray &M)
{
maxSize = M.maxSize;
lenght = M.lenght;
A = new int[maxSize];
for(int i = 0; i < M.lenght; i++)
A[i] = M.A[i];
}
//Adds the elements of the array with each other and returns the result
const myArray& myArray::operator +(const myArray& secondArray)
{
try
{
if(lenght != secondArray.lenght)
throw myException(10, "Different sizes!");
myArray result(secondArray);
for(int i = 0; i < lenght;i++)
result.A[i] = A[i] + secondArray.A[i];
return result;
}
catch(myException& e)
{
cout << e;
}
}
//Subtracts the elements of the array with each other and returns the result
const myArray& myArray::operator -(const myArray secondArray)
{
try
{
if(lenght != secondArray.lenght)
throw myException(10, "Different sizes!");
myArray result(secondArray);
for(int i = 0; i < lenght;i++)
result.A[i] = this->A[i] - secondArray.A[i];
return result;
}
catch(myException& e)
{
cout << e;
}
}
//Gets the dot product of 2 vectors
const int myArray::operator *(const myArray& secondArray)
{
try
{
if(lenght != secondArray.lenght)
throw myException(10, "Different sizes!");
int result = 0;
for(int i = 0; i < lenght;i++)
result += this->A[i] * secondArray.A[i];
return result;
}
catch(myException& e)
{
cout << e;
}
}
//Divides the elements of the array with each other and returns the result
const myArray& myArray::operator /(const myArray secondArray)
{
try
{
if(lenght != secondArray.lenght)
throw myException(10, "Different sizes!");
myArray result(secondArray);
for(int i = 0; i < lenght;i++)
result.A[i] = this->A[i] / secondArray.A[i];
return result;
}
catch(myException& e)
{
cout << e;
}
}
//Adds the elements of the array with an int and returns the result
const myArray& myArray::operator +(int A)
{
myArray result(*this);
for(int i = 0; i < lenght;i++)
result = this->A[i] + A;
return result;
}
//Subtracts the elements of the array with an int and returns the result
const myArray& myArray::operator -(int A)
{
myArray result(*this);
for(int i = 0; i < lenght;i++)
result = this->A[i] - A;
return result;
}
//Gets the dot product of a vector multiplied by an int
const int myArray::operator *(int A)
{
int result = 0;
for(int i = 0; i < lenght;i++)
result += this->A[i] * A;
return result;
}
//Divides the elements of the array with an int and returns the result
const myArray myArray::operator /(int A)
{
myArray result(*this);
for(int i = 0; i < lenght;i++)
result = this->A[i] / A;
return result;
}
//increments every element in the array by 1(Pre-increment)
const myArray myArray::operator ++()
{
for(int i = 0; i < lenght; i++)
++A[i];
return *this;
}
//increments every element in the array by 1(Post-increment)
const myArray myArray::operator ++(int)
{
myArray temp(maxSize);
for(int i = 0; i < lenght; i++)
temp.A[i] = A[i]++;
return temp;
}
//decrements every element in the array by 1(Pre-decrement)
const myArray myArray::operator --()
{
for(int i = 0; i < lenght; i++)
--A[i];
return *this;
}
//decrements every element in the array by 1(Post-decrement)
const myArray myArray::operator --(int)
{
myArray temp(maxSize);
for(int i = 0; i < lenght; i++)
temp.A[i] = A[i]--;
return temp;
}
//Makes every element in the array negative
myArray myArray::operator -()
{
for(int i = 0; i < lenght; i++)
A[i] = -A[i];
return *this;
}
//returns the number in the array using []
int myArray::operator [](int ind) const
{
try
{
if(ind > lenght)
throw myException(60, "Array index out of bounds");
return A[ind];
}
catch(myException& e)
{
cout << e;
}
}
//Assignment operator
myArray& myArray::operator=(const myArray& B)
{
delete [] A;
A = new int[B.maxSize];
lenght = B.lenght;
maxSize = B.maxSize;
for(int i = 0; i < B.lenght; i++)
{
A[i] = B.A[i];
}
return (*this);
}
//pushes the value inserted to the next available spot in the array
void myArray::push(int n)
{
try
{
if(lenght == maxSize)
throw myException(30, "Not enough space");
if(lenght == 0)
{
A[0] = n;
lenght++;
}
else
{
for(int i = 0; i < lenght; i++)
{
if(i+1 == lenght)
{
A[i+1] = n;
lenght++;
break;
}
}
}
}
catch(myException& e)
{
cout << e;
}
}
//Removes the last element in the array and returns it
int myArray::pop()
{
try
{
if(lenght <= 0)
throw myException(60, "Array index out of bounds");
int temp = A[lenght - 1];
A[lenght - 1] = NULL;
lenght--;
return temp;
}
catch(myException& e)
{
cout << e;
}
}
inserts an element at the specified position
void myArray::insert(int n, int pos)
{
try
{
if(pos > lenght)
throw myException(60, "Array index out of bounds");
for(int i = 0; i <= lenght; i++)
{
if(i == pos)
{
A[i-1] = n;
}
}
}
catch(myException& e)
{
cout << e;
}
}
//removes an element at a specified position an returns the value.
int myArray::remove(int pos)
{
try
{
if(pos < 0 || (pos > lenght -1))
throw myException(50, "Invalid Position");
int temp = A[pos];
A[pos] = NULL;
for(int i = pos; i < lenght; i++)
{
A[i] = A[i+1];
}
return temp;
}
catch(myException& e)
{
cout << e;
}
}
//Re sizes the entire array
void myArray::resize(int newSize)
{
int *B;
B = new int[newSize];
maxSize = newSize;
for(int i = 0; i < lenght; i++)
B[i] = A[i];
delete[] A;
A = B;
}
#endif
This is just a dummy main to test everything on the myArray class
main.cpp
#include "myArray.h"
int main()
{
int num;
myArray vector1;
myArray vector2(5);
myArray vector3;
vector1.resize(5);
//cout << "Max Size: " << vector1.getMaxSize() << endl;
for(int i = 0; i < 4; i++)
{
cin >> num;
vector1.push(num);
}
for(int i = 0; i < 4; i++)
{
cin >> num;
vector2.push(num);
}
vector3 = vector1 + vector2;
for(int i = 0; i < 4; i++)
cout << vector3.pop() << endl;
}
You create dynamic array with zero size in default constructor.
But in push method you try to set value to it if it's length is zero.
In C++ standard it says:
The effect of dereferencing a pointer returned as a request for zero
size is undefined.
You can only delete it. Fix your push method

How to initialize a class Object of Typename T?

For a C++ class I am taking, I am creating a Vector Library. We are not allowed to use the built in vector library, of course, and I have decided to use arrays in my 'myvector' class.
I am currently trying to test my code and I am not sure how to create an object of class myvector.
The error I get is Incomplete type is not allowed.
main.cpp:
#include "my_vectorHeader.h"
using namespace std;
int main(){
myvector<int> vector = new myvector<int>(3);
}
my_vectorLib.cpp:
#include "my_vectorHeader.h"
#include iostream
#include exception
using namespace std;
template<typename T> class myvector {
private:
int vector_size, //holds current size
vector_capacity; //holds current capacity
public:
//constructors
myvector<T>(int length){
T vector[length];
vector_size = length;
vector_capacity = length;
}
myvector<T>(const T& doppelganger){
T vector = doppelganger;
while(vector[vector_size] != NULL)
vector_size++;
}
myvector<T>(const T& dat_arr, int arr_size){
vector_size = arr_size;
vector_capacity = arr_size;
for(int i = 0; i < arr_size; i++)
vector[i] = dat_arr[i];
}
~myvector(){ //destructor
delete [] vector;
delete myvector;
}
myvector& myvector::operator[](int index){ //override []
try{
throw vector[index];
} catch(exception e){
cout << e.what() << endl;
}
return vector[index];
}
T at(int index){
return vector[index];
}
int size(){
return vector_size;
}
int capacity(){
return vector_capacity;
}
bool empty(){
if(size() > 0)
return false;
else
return true;
}
void resize(int new_size){
T vector_copy[new_size];
for(int i = 0; i < new_size; i++){
if(i >= vector_size)
vector_copy[i] = NULL;
else
vector_copy[i] = vector[i];
if(new_size > capacity)
capacity = new_size;
}
vector_size = new_size;
delete [] vector;
T *vector;
vector = vector_copy;
for(int i = 0; i < vector_size; i++)
vector[i] = vector_copy[i];
delete [] vector_copy;
}
void reserve(int new_capacity){
if(new_capacity < vector_size){
cout << "Error. Newly provided vector capacity is smaller than the current vector size. The capacity is " << vector_capacity << " and has not been changed.";
} else {
vector_capacity = new_capacity;
}
}
T pop_back(){
T return_val = vector[size() - 1];
resize(size() - 1);
return return_val;
}
void push_back(T new_val){
resize(size() + 1);
vector[size() - 1] = new_val;
}
void assign(int position, T new_val){
vector[position] = new_val;
}
void clear(){
for(int i = 0; i < size(); i++)
vector[i] = NULL;
}
void erase(int position){
vector[position] = NULL;
do{
vector[position] = vector[position + 1];
}while(position != NULL);
resize(size() - 1);
}
void erase(int in, int between){
int i = in + 1, j = between;
while(i < between){
vector[i] = vector[j];
vector[j] = NULL;
i++, j++;
}
resize(between);
}
void insert(int index, T new_val){
for(int i = size + 1; i > index; i--)
vector[i] = vector[i - 1];
vector[index] = new_val;
}
};
Declaration and implementation of templates should be in the same file(or implementation should be included too). Also this
myvector<int> vector = new myvector<int>(3);
is incorrect(new returns pointer) and unnecessary. Just use
myvector<int> vector(3);
Put the class (all the code) found at my_vectorLib.cpp in your my_vectorLib.h As #soon pointed you, templates classes (unless specialized) need to be at the header file (the one you include at main.cpp which where the class is instantiated, which means the compiler generates the actual code when you use the template).