Converting from Money class to Int Fails - c++

Compilation error is:
'initializing': cannot convert from 'int' to 'Money'
File: genericarray.h
Line: 13
This is my main function
int main()
{
genericArray<Money>m3(5);
Money d(-1, 89);
Money a(10, 5);
Money b(10, 5);
Money c(43, 7);
Money k(50, 6);
Money m(10, 20);
Money bonus(5, 0);
m3.elements[0] = a;
m3.elements[1] = b;
m3.elements[2] = c;
m3.elements[3] = k;
m3.elements[4] = m;
m3.total = m3.sum();
m2.total = m2.sum();
m1.total = m1.sum();
return 0;
}
This is my Assignment operator overloading of Money class and Money class itself
class Money
{
private:
int lira;
int kurus;
public:
Money() { lira = 0; kurus = 0; }
Money(int a, int b);
~Money() {}
void operator=(const Money& money2) { this->lira = money2.lira; this->kurus = money2.kurus; }
void operator=(int l) { this->lira = l; this->kurus = 0; }
This is my genericArray class with sum() function
template <class Type>
class genericArray
{
private:
int size;
public:
Type* elements;
Type total;
Type sum()
{
Type sumAll = 0;
for (int i = 0; i < size; i++)
{
sumAll += elements[i];
}
if (sumAll > 100)
sumAll += 5;
return sumAll;
}
genericArray() { elements = NULL; size = 0; }
genericArray(int arrSize) { elements = new Type[arrSize]; size = arrSize; }
~genericArray() { delete[] elements; }
};

Writing a new constructor with a single int parameter solved the problem:
Money(const int a)
{
if (a < 0) throw "The amount of money can not be below zero!";
this->lira = a;
this->kurus = 0;
}
The point is that
Type sumAll = 0;
calls only the constructor which takes only 1 int instead of calling the default constructor and the assignment operator.

Related

a user defined class of ARRAY in c++ with pointer

This code is a class of arrays definition that uses dynamic memory to allocate memory. The command ArrayClass temp(_size); in operator+ method gives the following runtime error.
Unhandled exception at 0x7715C54F in ArrayClass.exe: Microsoft C++
exception: std::bad_array_new_length at memory location 0x0033FB10.
If we convert this command to ArrayClass *temp = new ArrayClass(_size), no error will be occured. But the new object temp that was allocated by new operator will not be deleted.
Does anyone have a solution?
#include <iostream>
using namespace std;
class ArrayClass {
private:
int _size;
float* _ar;
public:
ArrayClass(const int& size) {
_size = size;
_ar = new float[_size];
}
~ArrayClass() {
delete[]_ar;
}
const ArrayClass& operator=(const ArrayClass& RightOperand) {
if (this != &RightOperand) {
if (this->_size != RightOperand._size) {
delete[] this->_ar;
this->_size = RightOperand._size;
this->_ar = new float[this->_size];
}
for (int i = 0; i < RightOperand._size; i++)
{
this->_ar[i] = RightOperand._ar[i];
}
}
return *this;
}
const ArrayClass& operator+(const ArrayClass& RightOperand) {
//*this+RightOperand
if (this->_size != RightOperand._size) {
cout << "different Size";
exit(1);
}
ArrayClass temp(_size);
for (int i = 0; i < _size; i++)
{
temp._ar[i] = this->_ar[i] + RightOperand._ar[i];
}
return temp;
}
};
int main() {
ArrayClass x(5), y(5), z(5);
x = y;
z= x + y;
return 0;
}

double free or corruption (fasttop) -- c++

I just came across a strange problem. I will paste the full code below:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// declare a base class
class Base
{
public:
Base();
Base(int n, int arr[2]);
Base(const Base &base);
Base &operator=(const Base &rhs);
int getSize() const;
int *getA() const;
~Base();
private:
int *a;
int size;
};
class Case
{
public:
Case();
Case(int n, int arr[2]);
Case(const Case &rhs);
Case &operator=(const Case &rhs);
int getSize() const;
int *getA() const;
~Case();
private:
int *a;
int size;
};
class Dase
{
public:
Dase();
Dase(int bSize, int barr[2], int cSize, int carr[2]);
Dase(const Dase &dase);
Dase &operator=(const Dase &rhs);
Base getB() const;
Case getC() const;
~Dase();
private:
Base b;
Case c;
};
// implementation
Base::Base() : size(0)
{
a = NULL;
}
Base::Base(int n, int arr[2]) : size(n)
{
a = new int[n];
for (int i = 0; i < size; i++)
a[i] = arr[i];
}
Base::Base(const Base &base)
{
size = base.getSize();
a = new int[size];
for (int i = 0; i < size; i++)
a[i] = base.getA()[i];
}
Base &Base::operator=(const Base &rhs)
{
if (this == &rhs)
return *this;
size = rhs.getSize();
delete[] a;
a = new int[size];
for (int i = 0; i < size; i++)
a[i] = rhs.getA()[i];
return *this;
}
int *Base::getA() const
{
return a;
}
int Base::getSize() const
{
return size;
}
Base::~Base()
{
delete[] a;
}
Case::Case() : size(0)
{
a = NULL;
}
Case::Case(int n, int arr[2]) : size(n)
{
a = new int[n];
for (int i = 0; i < size; i++)
a[i] = arr[i];
}
Case::Case(const Case &rhs)
{
size = rhs.getSize();
a = new int[size];
for (int i = 0; i < size; i++)
a[i] = rhs.getA()[i];
}
Case &Case::operator=(const Case &rhs)
{
if (this == &rhs)
return *this;
size = rhs.getSize();
delete[] a;
a = new int[size];
for (int i = 0; i < size; i++)
a[i] = rhs.getA()[i];
return *this;
}
int *Case::getA() const
{
return a;
}
int Case::getSize() const
{
return size;
}
Case::~Case()
{
delete[] a;
}
// implement class Dase
Dase::Dase() : b(Base()), c(Case())
{
// delebrately left empty
}
Dase::Dase(int bSize, int barr[2], int cSize, int carr[2])
{
b = Base(bSize, barr);
c = Case(cSize, carr);
}
Dase::Dase(const Dase &dase)
{
b = dase.getB();
c = dase.getC();
}
Dase &Dase::operator=(const Dase &rhs)
{
if (this == &rhs)
return *this;
b = rhs.getB();
c = rhs.getC();
return *this;
}
Base Dase::getB() const
{
return b;
}
Case Dase::getC() const
{
return c;
}
Dase::~Dase()
{
b.~Base();
c.~Case();
}
In the above code, I defined 3 classes: Base, Case, Dase. I included their declarations and implementations. The following is the main code:
#include "classes.h"
int main()
{
int arr[2] = {1, 2};
int brr[2] = {3, 4};
Dase d1(2, arr, 2, brr);
Dase d2;
d2 = d1;
}
This is a very simple main code, but I got "double free or corruption (fasttop)" error in the runtime.
I noticed that when I deleted the destructor in the class Dase, this problem went away. What shall I do to fix this problem if I want to keep the destructor for Dase? Shall I change its implementation?
Thank you!
You should not call destructors explicitly. It's done automatically.
So, replace
Dase::~Dase()
{
b.~Base();
c.~Case();
}
with
Dase::~Dase()
{
}

binary '+=': no global operator found when trying to add a object to an array of objects

I am trying to add a Complex number, represented in Complex class to an array of complex.
#pragma once
class Complex
{
private:
int re, im;
public:
Complex() {};
Complex(int a, int b) { re = a; im = b; }
Complex(const Complex &);
Complex& operator=(const Complex &);
//operators overloading
bool operator==(Complex);
//member function
void print();
};
class Multime
{
private:
Complex *array;
static int nrElem;
int dim;
public:
Multime();
Multime(int a) { dim = a; nrElem = 0; array = new Complex[dim]; }
~Multime();
//Operators overloading
Multime& operator += (Complex b);
Multime& operator =(const Multime &);
//member function
void print();
};
Functions.cpp
#include <iostream>
#include "Multime.h"
using namespace std;
Complex::Complex(const Complex &a)
{
re = a.re;
im = a.im;
}
Complex& Complex::operator= (const Complex&a)
{
re = a.re;
im = a.im;
return *this;
}
void Complex::print()
{
cout << re << "+" << im << "i" << endl;
}
bool Complex::operator==(const Complex a)
{
return (re == a.re && im == a.im);
}
//Multime
//
Multime::Multime()
{
dim = 0;
nrElem = 0;
array = nullptr;
}
Multime::~Multime()
{
if (nullptr != array)
{
delete[] array;
}
}
void Multime::print()
{
for (int i = 0; i < nrElem; ++i)
{
array[i].print();
}
cout << endl;
}
Multime& Multime::operator +=(Complex a)
{
int g = 0;
if (nrElem < dim)
{
for (int i = 0; i < nrElem; ++i)
{
if (array[i] == a)
{
g = 1;
}
}
}
if (!g) //Element not found, can insert
{
array[nrElem++] = a;
}
return *this;
}
Multime& Multime::operator =(const Multime & a)
{
dim = a.dim;
array = new Complex[dim];
for (int i = 0; i < nrElem; ++i)
{
array[i] = a.array[i];
}
return *this;
}
In main I wrote the initialization for the static int Multime::nrElem = 0; after preprocessor directivesand and in main(void):
Multime a[50];
Complex f(2, 5), b(1, 3), c(5, 4);
a+=f;
but I get the error: binary '+=': no global operator found.I don't wanna use a friend function for +. I tried to create separate functions for + and = but the error is still there.
LE. The problem was in main a it's an array of Multime. Correct one, using initialization constructor: Multime a(50);
a+=f;
is not valid since a is an array of Multime, not an object of type Multime.
If you want to use the operator+= on one object, you could use
a[0] += f;
If you want to use it for all the objects in the array, use a loop.
for ( auto& item : a )
{
item += f;
}

"No instance of constructor "PlayerData::PlayerData" matches the argument list." error Visual Studio is giving me when I try to run the program

Header File
#pragma once
#ifndef PLAYERDATA_H
#define PLAYERDATA_H
#include <string>
using namespace std;
class PlayerData
{
private:
Private member variables
static const int SIZE = 10;
string name; //Player Name
int jnum; //Jersey Number
string team; //Player Team
string position; //Player position
int points[SIZE]; // Array of points for last 10 games
int rebounds[SIZE]; // Array of rebounds for last 10 games
int assist[SIZE]; // Array of assist for last 10 games
double ap = 0.0; // Average number of points
double ar = 0.0; // Average number of rebounds
double aa = 0.0; // Average number of assits
public:
Constructor to initialize data if no data is passed
// Constructor #1
PlayerData()
{
jnum = 0;
name = "";
team = "";
position = "";
for (int i = 0; i < SIZE; i++)
{
points[SIZE] = 0;
rebounds[SIZE] = 0;
assist[SIZE] = 0;
}
}
// Constructor #2
Constructor to accept parameter. Collects jersey number, name, team name, position, array of points for last 10 games, array of rebounds for last 10 games, array of assist for last 10 games.
PlayerData( int jn, string n, string t, string pos, int p[SIZE], int r[SIZE], int a[SIZE])
{
jnum = jn;
name = n;
team = t;
position = pos;
for (int i = 0; i < SIZE; i++)
{
points[SIZE] = p[SIZE];
rebounds[SIZE] = r[SIZE];
assist[SIZE] = a[SIZE];
}
}
// Mutator Function
void setJersery(int jn)
{
jnum = jn;
}
void setName(string n)
{
name = n;
}
void setTeam(string t)
{
team = t;
}
void setPosition(string pos)
{
position = pos;
}
void setPoints(int p[SIZE])
{
for (int z = 0; z < SIZE; z++)
{
points[SIZE] = p[SIZE];
}
}
void setRebounds(int r[SIZE])
{
for (int z = 0; z < SIZE; z++)
{
rebounds[SIZE] = r[SIZE];
}
}
void setAssist(int a[SIZE])
{
for (int z = 0; z < SIZE; z++)
{
assist[SIZE] = a[SIZE];
}
}
// Acessor methods
string getName()
{
return name;
}
int getJersey()
{
return jnum;
}
string getTeam()
{
return team;
}
string getPosition()
{
return position;
}
int getPoints()
{
return points[SIZE];
}
int getRebounds()
{
return rebounds[SIZE];
}
int getAssist()
{
return assist[SIZE];
}
/*
double averageP(int p[], const int SIZE);
double averageR(int r[], const int SIZE);
double averageA(int a[], const int SIZE);
*/
void averageP(int p[], const int SIZE);
void averageR(int r[], const int SIZE);
void averageA(int a[], const int SIZE);
double getAP()
{
return ap;
}
double getAR()
{
return ar;
}
double getAA()
{
return aa;
}
};
#endif // !PLAYERDATA_H
Calculates average points,rebounds, assist from the arrays that were passed.
PlayerData.cpp
#include "PlayerData.h"
using namespace std;
// Calculate average points
void PlayerData::averageP(int p[], const int s)
{
for (int c = 0; c < s; c++)
{
ap += p[c];
}
ap /= s;
//return ap;
}
// Calculate average rebounds
void PlayerData::averageR(int r[], const int s)
{
for (int c = 0; c < s; c++)
{
ar += r[c];
}
ar /= s;
//return ar;
}
// Calculate average assist
void PlayerData::averageA(int a[], const int s)
{
for (int c = 0; c < s; c++)
{
aa += a[c];
}
aa /= s;
//return aa;
}
Main
#include <iostream>
#include <iomanip>
#include "PlayerData.h"
using namespace std;
int main()
{
const int SIZE = 10;
int points[SIZE] = { 10,10,10,10,10,10,10,10,10,10 };
int assist[SIZE] = { 2,2,2,2,2,2,2,2,2,2, };
int rebounds[SIZE] = { 3,3,3,3,3,3,3,3,3,3 };
Here is where the problem occurs. The compiler marks under the 6 as if the int is not part of the arguments for the constructor. I'm not sure why it is doing this. I receive this message "No instance of constructor "PlayerData::PlayerData" matches the argument list."
PlayerData player1(6, "Jimmy Butler", "Chicago Bulls", "Forward", points[SIZE], rebounds[SIZE], assist[SIZE]);
getchar();
return 0;
}
Constructor requires an array of integers and in main you are passing a pointer to int. If you want to pass the whole array you should delete the [SIZE] because that is translated as (if SIZE is 5 for example) "give me the 6th element of 5 element array".
Try calling it like this.
PlayerData player1(6, "Jimmy Butler", "Chicago Bulls", "Forward", points, rebounds, assist);

Array of derived class stored in parent class

I don't think I quite understand how to store an array of a derived class in its parent class.
I keep getting errors
Error C3646 'list': unknown override specifier
Error C2065 'list': undeclared identifier
Here is the code I have
#include <iostream>
#include <string>
using namespace std;
class GameScores
{
public:
GameEntry list[9];
void inputList(GameEntry x);
void sortList();
void removeList(int r);
void printList();
GameScores();
};
class GameEntry :public GameScores
{
public:
GameEntry(const string& n = "", int s = 0, const string d = "1/1/99");
string getName() const;
int getScore() const;
string getDate() const;
string setName(string n);
int setScore(int s);
string setDate(string d);
private:
string name;
int score;
string date;
};
GameScores::GameScores()
{
GameEntry list[9];
}
void GameScores::inputList(GameEntry x)
{
for (int i = 0; i < 10; i++)
if (x.getScore() >= list[i].getScore())
{
list[i + 1] = list[i];
list[i] = x;
}
}
void GameScores::sortList()
{
GameEntry swap;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10 - 1; j++)
{
if (list[j].getScore() > list[j].getScore() + 1)
{
swap = list[j];
list[j] = list[j + 1];
list[j + 1] = swap;
}
}
}
}
void GameScores::removeList(int r)
{
for (int i = r; i < 10; i++)
list[i - 1] = list[i];
list[9].setScore(0);
list[9].setName(" ");
list[9].setDate(" ");
}
void GameScores::printList()
{
cout << "Top Scores" << endl;
for (int i = 0; i < 10; i++)
cout << list[i].getScore() << " " << list[i].getName() << " " << list[i].getDate() << endl;
}
GameEntry::GameEntry(const string& n, int s, const string d) // constructor
: name(n), score(s), date(d) { }
// accessors
string GameEntry::getName() const { return name; }
int GameEntry::getScore() const { return score; }
string GameEntry::getDate() const { return date; }
string GameEntry::setName(string n)
{
name = n;
}
int GameEntry::setScore(int s)
{
score = s;
}
;
string GameEntry::setDate(string d)
{
date = d;
}
int main()
{
GameEntry p1("John", 90, "9/9/98"), p2("Jane", 95, 8/21/98), p3("Bob", 60, "7/11/99"), p4("Jo", 92, "6/4/97");
GameScores topScores;
topScores.inputList(p1);
topScores.inputList(p2);
topScores.inputList(p3);
topScores.inputList(p4);
topScores.printList();
return 0;
}
This design is very questionable. What purpose is being served by making the second class inherit the first? It looks like you'd end up with each member of the array containing an additional array with all its siblings. Don't you want only one array? You need to rethink this from an earlier point.
If you really have a reason for a parent class to contain an array of the child class, maybe you should define an interface (abstract base class) that both classes implement.
To use GameEntry as a type in your GameScores class , you must forward-declare the class like so :
class GameEntry;
class GameScores
{
public:
GameEntry list[9];
void inputList(GameEntry x);
void sortList();
void removeList(int r);
void printList();
GameScores();
};