Change poly p1, p2; on poly p1(3), p2(3); .
p.no_term has a value of 3 , however look at your poly constructor:
poly::poly(int d=0) { no_term = d; term_ptr = new term[no_term]; }
You create an array of length 0 . In addition, there is no need to use a pointer in your code. Here is an example using std::vector<term> :
#include<iostream> #include <vector> using namespace std; class term { public: int exp; int coeff; }; class poly { public: std::vector<term> term_vec; int no_term; poly(int d); friend istream& operator>>(istream& in, poly& p); friend ostream& operator<<(ostream& out, const poly& p); friend poly operator+(const poly& p1, const poly& p2); }; poly::poly(int d=0) : term_vec(d), no_term(d) { } istream& operator>>(istream& in, poly& p) { in>>p.no_term; p.term_vec.resize(p.no_term); for(int i= 0; i<p.no_term; i++) { in>> p.term_vec[i].coeff; in>> p.term_vec[i].exp; } return in; } ostream& operator<<(ostream& out, const poly& p) { out<<"coeff"<<" "<<"power"<<endl; for(int i = 0; i< p.no_term; i++) out<<p.term_vec[i].coeff<<" "<<p.term_vec[i].exp<<endl; return out; } int main(void) { poly p1, p2; cin>>p1; cin>>p2; cout<<p1; cout<<p2; return 0; }
source share