NULL data stored by overloaded istream - c++

This is part of my polynomial.cpp to get terms by overloading istream
void Newterm(float coef, int deg) {
if (terms == capacity) {
capacity *= 2;
Term* tmp = new Term[capacity];
copy(termArray, termArray + terms, tmp);
termArray = tmp;
delete[] tmp;
}
termArray[terms].degree = deg;
termArray[terms++].coef = coef;
}
friend istream& operator >> (istream& is, Polynomial& pl) {
cout << "number of terms : ";
int t; is >> t;
cout << endl;
float coeff;
int degree;
for (int i = 0; i < t;i++) {
cout << i + 1 << "'s term: ";
is >> coeff >> degree;
pl.Newterm(coeff, degree);
}
return is;
};
of course, i tried to figure out whaaat made this result..
tried:
removing 'for' loop
this actually worked.. but it only works when terms=1
firstly creating term and input data
Newterm(0,0);
is>>pl.termArray[i].coef>>pl.termArray[i].degree;
it couldn't fix anything...
so i think it has to do with loops..
but whyyyy?

Using std::vector instead of doing your own memory managment
(why reinvent the wheel if there is a tested solution in the standard library)
#include <iostream>
#include <vector>
struct Term final
{
Term() = default;
~Term() = default;
Term(int d, double c) :
degree{ d },
coef{ c }
{
}
int degree{ 0 };
double coef{ 1.0 };
};
class Polynomial final
{
public:
Polynomial() = default;
~Polynomial() = default;
explicit Polynomial(const std::initializer_list<Term> terms) :
m_terms{ terms }
{
}
void add(const Term& term)
{
m_terms.push_back(term);
}
private:
std::vector<Term> m_terms;
};
std::istream& operator>>(std::istream& is, Polynomial& polynomial)
{
std::size_t n{ 0 }; // indices are not ints the can't be < 0
is >> n;
for (std::size_t i = 0; i < n; ++i)
{
Term term{};
is >> term.coef;
is >> term.degree;
polynomial.add(term);
}
return is;
}
int main()
{
// to show you that std::vector can handle all the memory managment for you
// constructor with an initializer list that adds 3 terms
// that's also why the Term has a constructor, it is to make it work with
// initializer list
Polynomial p{ { 1,2.0 }, { 2,4.0 }, { 1,-1.0 } };
}

Related

Strange copy constructor and destructor error

I have a class and i keep getting some error from the destructor.
This is the clas:
#pragma once
class Number
{
int bas;
char* val;
public:
Number(const char* value, int base);
Number(const Number& x);
~Number();
void SwitchBase(int newBase);
void Print();
int GetDigitsCount();
int GetBase();
};
This is the cpp file:
#include "Number.h"
#include <iostream>
Number::Number(const char* value, int base)
{
int a = -1;
do
{
a++;
} while (value[a] != '\0');
val = new char[a + 1];
for (int i = 0; i <= a; i++)
val[i] = value[i];
bas = base;
}
Number::Number(const Number& x)
{
int a = -1;
bas = x.bas;
do
{
a++;
} while (x.val[a] != '\0');
delete[]val;
val = new char[a + 1];
int i;
for (i = 0; i <= a; i++)
val[i] = x.val[i];
}
Number::~Number()
{
delete[]val;
}
void Number::Print()
{
std::cout << "Numarul este: " << val<< std::endl << "Baza este: " << bas<<std::endl;
}
int Number:: GetDigitsCount()
{
int l = 0;
do
{
l++;
} while (val[l] != '\0');
return l;
}
This is the main:
int main()
{
Number x("123", 10),y("111",10),z("0",10);
z = y;
z.Print();
}
I keep getting this error:
Invalid address specified to RtlValidateHeap( 010C0000, 010C8DD8 )
If i do this change in main it works properly but it is not really what I want...
int main()
{
Number x("123", 10),y("111",10);
Number z = y;
z.Print();
}
How can I solve this? I can't figure it out...
Your Number class is missing an assignment operator. Since you use the assignment operator in main the default assignment operator will cause a double delete when you exit main and this explains the error.
It also explains why the error goes away when you change main to use the copy constructor instead of the assignment operator.
You should look at the copy and swap idiom to show how to easily and efficiently implement copy constructors and assignment operators.
Alternatively you could also use std::string instead of manually allocating memory. This would eliminate the need to write a destructor, copy constructor and assignment operator. That's the best solution.
This is an example of how code may look like using std::string:
#include <iostream>
#include <string>
class Number
{
int bas;
std::string val;
public:
Number(std::string, int base);
Number(const Number& number);
Number& operator= (const Number& number);
~Number()=default;
void Print();
int GetDigitsCount();
};
Number::Number(std::string value, int base)
{
val=value;
bas=base;
}
Number::Number(const Number& number)
{
val=number.val;
bas=number.bas;
}
Number& Number::operator= (const Number& number)
{
val=number.val;
bas=number.bas;
return *this;
}
void Number::Print()
{
std::cout << "Numarul este: " << val<< std::endl << "Baza este: " << bas<<std::endl;
}
int Number:: GetDigitsCount()
{
return val.size();
}
int main()
{
Number x("123", 10),y("111",10),z("0",10);
Number k(y);
k.Print();
}

Data loss every time I push an object into a vector

I have a school project in which I am supposed to build a template class Vanzare meaning sale. I have 2 STL vectors, one for the cars that are in stock, and one for the cars that are sold, and 2 variables that count how many cars are in stock and how many cars are sold.
The class is supposed to have the -= operator overloaded, and it's supposed to sell a car, meaning deleting it from the stock vector (named stoc) and adding it to the sold vector (named vandut).
I also overloaded the += operator to add a car to stock.
The types of cars I have are all derived from the base class Masina, and some of them have extra fields.
The problem is that whenever I use += or -= ( or push_back() in general) for anything that has extra fields (compared to the base class), it breaks the previous elements from the vector. So I can't store any derived objects without loss of information.
I was also told that making a specialization of the whole class might help, but it didn't.
The template class starts around line 300 (I didn't know how to highlight it sorry). I am sorry if what I wrote wasn't clear, I am kinda new to all of this object oriented stuff. Thank you in advance!
Edit: I tried my best to slim the program down as much as I can, but it still has 250 lines of code. I also renamed (hopefully everything) to English. The field sh still gets lost when I add an object to the vector.
#include <iostream>
#include <string.h>
#include <vector>
#include <ctime>
using namespace std;
class Car
{
int capacity;
float length;
int price;
int year;
public:
int getYear();
void setPrice(int);
int getPrice();
Car();
~Car();
Car(int , float , int , int);
Car(const Car&);
friend istream& operator>>(istream& , Car&);
friend ostream& operator<<(ostream& , Car&);
friend class VAN;
};
int Car::getYear()
{
return year;
}
int Car::getPrice()
{
return price;
}
void Car::setPrice(int p)
{
price = p;
}
ostream& operator<<(ostream& out , Car& m)
{
out<<"capacity: "<<m.capacity<<"\nlength: "<<m.length<<"\nprice: "<<m.price<<"\nYear: "<<m.year;
return out;
}
istream& operator>>(istream& in , Car& m)
{
cout<<"capacity: ";
in>>m.capacity;
cout<<"length: ";
in>>m.length;
cout<<"price: ";
in>>m.price;
cout<<"Year: ";
in>>m.year;
return in;
}
Car::Car()
{
capacity = 0;
length = 0;
year = 0;
price = 0;
}
Car::Car(int lit , float lun , int an , int pre)
{
capacity = lit;
length = lun;
year = an;
price = pre;
}
Car::Car(const Car& m)
{
capacity = m.capacity;
length = m.length;
year = m.year;
price = m.price;
}
Car::~Car()
{
capacity = 0;
year = 0;
length = 0;
price = 0;
}
class VAN:public Car
{
int sh;
public:
void setSH(int);
int isSH();
VAN();
~VAN();
VAN(int , float , int , int , int);
VAN(const VAN&);
friend istream& operator>>(istream& , VAN&);
friend ostream& operator<<(ostream& , VAN&);
};
void VAN::setSH(int s)
{
if(s)
sh = 1;
else
sh = 0;
}
int VAN::isSH()
{
return sh;
}
ostream& operator<<(ostream& out , VAN& m)
{
out<<(Car&)m;
out<<endl<<"Second hand: "<<m.sh;
return out;
}
istream& operator>>(istream& in , VAN& m)
{
in>>(Car&)m;
cout<<"Second Hand: ";
int x;
in>>x;
if(x)
m.sh = 1;
return in;
}
VAN::VAN():Car()
{
;
}
VAN::~VAN()
{
;
}
VAN::VAN(int a , float b , int c, int d , int s):Car(a , b, c , d)
{
if(s)
sh = 1;
}
VAN::VAN(const VAN& m):Car(m)
{
;
}
template <class T>
class Sale
{
vector<T> stock;
vector<T> sold;
int nrSold;
int nrStock;
public:
Sale();
Sale<T>& operator += (T&);
template <class U>
friend ostream& operator<<(ostream& , Sale<U>& );
Sale<T>& operator -= (int);
};
template <class T> Sale<T>& Sale<T>::operator -= (int i)
{
nrStock--;
nrSold++;
sold.push_back(stock[i]);
stock.erase(stock.begin()+i);
time_t now = time(0);
tm *ltm = localtime(&now);
if(ltm->tm_mon == 5 || ltm->tm_mon == 6 || ltm->tm_mon == 7)
{
(sold[nrSold-1]).setPret((sold[nrSold-1].getPret()/10)*9);
}
return *this;
}
template <class T> Sale<T>::Sale()
{
nrSold = 0;
nrStock = 0;
}
template <class T> ostream& operator<<(ostream& out, Sale<T>& v)
{
out<<"\nWhat we have in stock:\n\n";
for(int i = 0; i < v.nrStock ; i++)
{
out<<v.stock[i]<<endl;
}
cout<<"\nWhat we sold:\n\n";
for(int i = 0; i < v.nrSold ; i++)
{
out<<v.sold[i]<<endl;
}
return out;
}
template <class T> Sale<T>& Sale<T>::operator += (T& t)
{
nrStock ++;
stock.push_back(t);
return *this;
}
int main()
{
VAN x;
cin>>x;
cout<<x;
Sale<VAN> v;
v += x;
v += x;
cout<<v;
}
There are logic errors in ALL of your VAN constructors:
in the default constructor, the sh member is not being initialized at all, so it's value is indeterminate.
In the conversion constructor, the sh member is not being initialized if the s parameter is 0, so it's value is indeterminate in that case. Your operator>> has a similar logic error that it is not updating the m.sh member if the input is 0.
in the copy constructor, the sh member is not being copied from m at all, so it's value is indeterminate.
When you push a VAN object into your vector, a copy of the object is made. And if the vector needs to reallocate its array to grow its capacity, new copies of existing elements are made. Since your copy constructor is broken, that is why you are losing your sh values.
Your VAN constructors need to look more like this instead 1:
VAN::VAN() : Car(), sh(0)
{
}
VAN::VAN(int a , float b , int c, int d , int s) : Car(a , b, c , d)
{
sh = (s != 0);
}
VAN::VAN(const VAN& m) : Car(m), sh(m.sh)
{
}
1: in the case of the copy constructor, you can actually omit it completely, and let the compiler auto-generate a suitable copy constructor for you.
And your operator>> needs to look more like this instead:
istream& operator>>(istream& in , VAN& m)
{
in >> (Car&)m;
cout << "Second Hand: ";
int x;
in >> x;
m.sh = (x != 0);
return in;
}
On a couple of side notes:
your sh member is declared as an int, but it clearly should be a bool instead.
VAN does not need to, and should not, be declared as a friend of Car. If VAN needs direct access to Car's private members, they should be declared as protected instead.

Writing an accessor method for inherited class with sparse member data?

Say I have a simple vector class, vec:
#include <iostream>
#include <stdlib.h>
class vec {
public:
vec() {}
// Constructor.
vec(int n) {
len = n;
data = new double[len];
}
// Destructor.
~vec() { delete [] data; }
// Accessor.
double & operator[](int i) const {
check_index(i);
return data[i];
}
// Other methods...
// ....
protected:
int len;
double * data;
void check_index(int i) const {
if(i < 0 || i >= len) {
std::cerr << "Bad access.\n";
exit(1);
}
}
};
Now suppose I have a special type of vector with sparse structure, e.g., where every even-index is zero. Call this oddvec. Instances of oddvec should be declared just as with the vec class, but underneath, the memory use should be efficient since only half the data is non-zero.
The accessor for the oddvec class should return 0 if the index is even, and return the odd-index element (stored sequentially) otherwise. There a couple problems with this:
The double & return type is violated if the index is even, since the constant value, 0, is returned.
It's not clear to me how to handle the situation when an even index element is used as an lvalue. E.g., v[0] = 3.0 should not be allowed in the oddvec class, but is perfectly acceptable in the vector class. We can't simply throw an error when even indexes are used, because even indexes are fine as long as the intention is as an rvalue.
How do I design the accessor function for the oddvec class, while both keeping the memory storage efficient and inheriting all the methods from the parent?
Non-working example of oddvec:
class oddvec : public vec {
public:
// Constructor.
oddvec(int n) {
len = n;
data = new double[len/2];
}
// Accessor (doesn't work!)
double & operator[](int i) const {
check_index(i);
if (i%2 == 0)
return 0;
else
return data[(i-1)/2];
}
};
Upon compilation:
main.cpp: In member function ‘double& oddvec::operator[](int) const’:
main.cpp:49:20: error: invalid initialization of non-const reference of type ‘double&’ from an rvalue of type ‘double’
return 0;
Working example using proxy classes:
I have implemented a proxy class as suggested in the answer below.
proxies.h
#ifndef PROXIES_H
#define PROXIES_H
#include <iostream>
#include <stdlib.h>
class proxy {
public:
proxy(int i, double v, double * d) {
index = i;
value = v;
data = d;
}
void operator=(double rhs) {
data[index] = rhs;
}
friend std::ostream & operator<<(std::ostream & outs, const proxy & p) {
outs << p.value;
return outs;
}
protected:
int index;
double value;
double * data;
};
class oddproxy : public proxy {
public:
oddproxy(int i, int v, double * d) : proxy(i, v, d) {}
void operator=(double rhs) {
if (index%2 == 0) {
std::cerr << "Even entries of oddvec are not assignable.\n";
exit(1);
}
data[index/2] = rhs;
}
};
#endif
vectors.h
#ifndef VECTORS_H
#define VECTORS_H
#include "proxies.h"
class vec {
public:
vec() {}
// Constructor.
vec(int n) {
len = n;
data = new double[len];
}
// Destructor.
~vec() { delete [] data; }
// Accessor.
proxy operator[](int i) const {
check_index(i);
return proxy(i, data[i], data);
}
inline int length() const { return len; }
// Other methods...
// ....
protected:
int len;
double * data;
void check_index(int i) const {
if(i < 0 || i >= len) {
std::cerr << "Bad access.\n";
exit(1);
}
}
};
class oddvec : public vec {
public:
// Constructor.
oddvec(int n) {
len = n;
data = new double[len/2];
}
// Accessor.
oddproxy operator[](int i) const {
check_index(i);
return oddproxy(i, (i%2 == 0) ? 0 : data[i/2], data);
}
};
#endif
main.cpp
#include <iostream>
#include "vectors.h"
int main () {
int N = 5;
vec V(N);
oddvec O(N);
for(int i=0; i < V.length(); i++) {
V[i] = i;
if(i%2 != 0) {
O[i] = i;
}
}
for(int i=0; i < O.length(); i++) {
std::cout << "V[" << i << "]=" << V[i] << ", "
<< "O[" << i << "]=" << O[i] << "\n";
}
O[0] = 13;
return 0;
}
output
V[0]=0, O[0]=0
V[1]=1, O[1]=1
V[2]=2, O[2]=0
V[3]=3, O[3]=3
V[4]=4, O[4]=0
Even entries of oddvec are not assignable.
You can use proxy object to do this.
simple sample code:
#include <iostream>
#include <vector>
using namespace std;
class very_odd_vector{
public:
class only_odd_proxy;
friend class only_odd_proxy;
only_odd_proxy operator [](int index);
int operator [](int index)const{return index%2==0?0:content[index/2];}
unsigned int size()const{return content.size()*2;}
private:
vector<int> content{1,3,5,7,9};
};
class very_odd_vector::only_odd_proxy{
public:
only_odd_proxy(very_odd_vector& vec,int index):vec(vec),index(index){}
operator int(){return index%2==0 ? 0 : vec.content[index/2];}
only_odd_proxy& operator =(int value){
if(index%2==0)
cout << "BAD OPERATION";//any error you want
else
vec.content[index/2] = value;
return *this;
}
private:
very_odd_vector& vec;
int index;
};
auto very_odd_vector::operator [](int index)->only_odd_proxy{return only_odd_proxy(*this,index);}
int main(){
very_odd_vector v;
cout << "reading value\n";
for(int i=0;i<v.size();++i)
cout << v[i] <<'\n';
cout << "writting value\n";
for(int i=0;i<v.size();++i){
cout << i << ':';
v[i]=10;
cout << '\n';
}
cout << "reading value\n";
for(int i=0;i<v.size();++i)
cout << v[i] <<'\n';
}
Edit for updated part of question :
I think this class will fit your need more.
//Both base and inherit class return this class
class maybe_readonly_proxy {
public:
maybe_readonly_proxy(double* data, bool readonly):readonly(readonly),data(data){}
maybe_readonly_proxy& operator=(double rhs) {
if(readonly){/*whatever error*/}
else {*data = rhs;}
return *this;
}
operator double()const{return *data;}
private:
bool readonly;
double * data;
};
You may need a variable to contain readonly (0 in this case) value, or modify the operator double() the check readonly state
Or just implement get and set method separately and do not use this proxy may be another choice.

c++ operator overloading with two non-class arguments (solved with proxy)

I'm learning about overloading and I've got curious if i could make an overloaded operator with two non-class arguments.
For example with vector class having x and y to call
vector += (4.5, -2.1);
Thank you!
EDIT
I've managed to do that, and also expanded to take as many arguments as user create. This is how it looks like:
//Point.hpp
class Point
{
friend class Proxy;
private:
double *val;
int i;
int amount;
public:
Point();
Point(const int&);
void Set(const int &);
double Get(const int &);
int Amount();
Proxy operator += (const double &add);
};
class Proxy
{
private:
int &i;
Point &temp_point;
public:
Proxy operator , (const double&);
Proxy(Point2D &, int&);
};
//Point.cpp
Point::Point()
{
this->amount = 2;
val = new double[this->amount];
val[0] = 0;
val[1] = 0;
};
Point::Point(const int &amount) : amount(amount)
{
val = new double[amount];
for (int i = 0; i < amount; i++)
{
val[i] = 0;
}
};
void Point::Set(const int &nr)
{
do
{
std::cout << "Give me value of " << nr << " coordinate: ";
std::cin.clear();
std::cin.sync();
std::cin >> val[nr];
if (std::cin.fail())
{
std::cout << "Try again, not acceptable...\n";
}
} while (std::cin.fail());
}
double Point::Get(const int &nr)
{
return val[nr];
}
int Point::Amount()
{
return this->amount;
}
Proxy Point::operator += (const double &add)
{
this->i = 0;
this->val[i++] += add;
return Proxy(*this, i);
}
Proxy::Proxy(Point &point, int &i) : temp_point(point), i(i)
{}
Proxy Proxy::operator , (const double &value)
{
temp_point.val[i++] += value;
return Proxy(temp_point, i);
}
//Source.cpp example
int main()
{
Point example(3);
example += 4.5, -2.3, 3.0;
for (int i = 0; i < example.Amount(); i++)
{
std::cout << example.Get(i) << " ";
}
std::cout << std::endl;
system("PAUSE");
return 0;
}
Hope somebody find it useful.
This won't work, because (4.5, -2.1) will invoke the built-in comma operator, and simply evaluate to -2.1. It would be possible to do this:
vector += 4.5, -2.1;
This works because , has lower precedence than +=. You can overload += so that it returns a proxy object, which in turn has an overloaded , operator that will append additional elements.
You could use an std::initializer_list
v & operator += (std::initializer_list<int> l)
{
sum = std::accumulate(l.begin(), l.end(), sum);
.....
You'll have to sligthly change your call to
vector += {1 , 2};
If you have a vector of pairs, a much more readable option would be to
vector += std::make_pair( 4.5, -2.1 );
Looks less magical, which usually a good thing.

Overloading i/o operators in C++ for polynomials

I got this project where I have to overload the i/o operators to read and write polynomials. Unfortunately I can't seem to get it to work.
I have the header file:
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include <iostream>
using namespace std;
class Polynomial
{
public:
Polynomial();
Polynomial(int degree, double coef[]);
int degree;
double coef[ ];
friend istream& operator>>(istream&,Polynomial& );
friend ostream& operator<<(ostream&,const Polynomial&);
virtual ~Polynomial();
};
#endif // POLYNOMIAL_H
and the cpp file:
#include "Polynomial.h"
#include<iostream>
#include<string>
using namespace std;
Polynomial::Polynomial()
{
//ctor
}
Polynomial::~Polynomial()
{
//dtor
}
Polynomial::Polynomial(int d, double c[])
{
degree = d;
double coef [degree+1];
for(int i = 0; i < d+1; i++)
{
coef[i] = c[i];
}
}
istream& operator>>(istream& x, const Polynomial& p)
{
cout<<"The degree: ";
x>>p.degree;
for(int i = 0; i < p.degree+1; i++)
{
cout<<"The coefficient of X^"<<i<<"=";
x>>p.coef[i];
}
return x;
}
ostream& operator<<(ostream& out, const Polynomial& p)
{
out << p.coef[0];
for (int i = 1; i < p.degree; i++)
{
out << p.coef[i];
out << "*X^";
out << i;
}
return out;
}
In the name I am trying to read a polynomial and then to write another one:
#include <iostream>
using namespace std;
#include "Polynomial.h"
int main()
{
Polynomial p1();
cin >> p1;
int degree = 2;
double coef [3];
coef[0]=1;
coef[1]=2;
coef[3]=3;
Polynomial p(degree, coef);
cout<<p;
return 0;
}
When I run the program it just freezes and I can't seem to find the error.
Any ideas?
Polynomial::Polynomial(int d, double c[])
{
degree = d;
double coef [degree+1];
for(int i = 0; i < d+1; i++)
{
coef[i] = c[i];
}
}
Here, you create local array coef (with non-standard C++ btw) and then assign to it. Your member coeff is not initialized to anything meanigfull (and makes little sense the way it is right now in the first place).
Instead of double coef[] you should use std::vector like this:
struct polynomial {
std::vector<double> coef;
// No need for member varaible degree, vector knows its lengths
polynomial (const std::vector<double> &coeffs) : coef (coeffs) {}
};
And then define all other constructors you need to do something meaningful. Alternatively, you can leave out constructors entirely and directly assign the coefficient vector. Then you can for example functions like
int degree (const polynomial &p) {
return p.coef.size() - 1;
}
or
std::ostream &operator << (std::ostream &out, const polynomial p) {
if (p.coef.size() == 0) {
out << "0\n";
return out;
}
out << p.coeff[0];
for (int i = 1; i < p.coef.size(); ++i)
out << " + " << p.coef[i] << "*X^i";
out << "\n";
return out;
}
(1)
double coef[];
This is non-standard approach to have un-sized/dynamic-sized array on stack. You better give the array some size, OR make it a pointer and allocate memory yourself; OR use vector<double>
(2)
You are creating a local variable in constructor, which will hide the member-variable in class. If you are using pointer approach, you need to allocate it properly here in constructor. With either approach, you should initialize the (member) variable coef with zeros, ideally.
(3)
Polynomial p1();
This effectively declares a function named p1 which would return a Polynomial and not a variable of tyoe Polynomial. You may want to use:
Polynomial p1;