I am trying to access an array with pointer in my c++ class.
below is my class.
#include <iostream>
using namespace std;
class Poly
{
friend istream &operator>>(istream &, Poly &);
friend ostream &operator<<(ostream &, const Poly &);
public:
Poly();
Poly(int);
Poly(int, int);
Poly(const Poly &);
~Poly();
int getCoeff(int) const;
int getMaxPow() const;
void setCoeff(int, int);
void setMaxPow(int);
Poly operator+(const Poly &) const;
Poly operator+=(const Poly &);
Poly operator-(const Poly &) const;
Poly operator-=(const Poly &);
Poly operator*(const Poly &) const;
Poly operator*=(const Poly &);
Poly operator=(const Poly &);
bool operator==(const Poly &) const;
bool operator!=(const Poly &) const;
private:
int* coeffPtr;
int maxPow;
};
below are my constructors
#include "poly.h"
#include <iostream>
using namespace std;
Poly::Poly() {
maxPow = 0;
int eq[1];
coeffPtr = &eq[0];
*coeffPtr = 0;
}
Poly::Poly(int coeff) {
maxPow = 0;
int eq[1];
coeffPtr = &eq[0];
*coeffPtr = coeff;
}
Poly::Poly(int coeff, int maxPower) {
maxPow = maxPower;
int eq[maxPower+1];
coeffPtr = &eq[0];
for(int i = 0; i < maxPower; i++)
{
*(coeffPtr+i) = 0;
}
*(coeffPtr+maxPower) = coeff;
}
Poly::Poly(const Poly &other) {
int eq[other.maxPow];
coeffPtr = &eq[0];
for(int i = 0; i < other.maxPow; i++)
{
*(coeffPtr+i) = other.getCoeff(i);
}
}
int Poly::getCoeff(int pow) const{
return *(coeffPtr+pow);
}
In my main method, the initial call to getCoeff(number) will return correct element in the array, but it seems that everything gets changed after that initial access.
e.g.,
Poly A(5,7);
A.getCoeff(7); //returns 5
A.getCoeff(7); //returns random memory
What am I doing it wrong?
Thanks you!