Destructor problems+ list display [duplicate] - c++

This question already has answers here:
What is The Rule of Three?
(8 answers)
Closed 7 years ago.
I have the following code:
The problem is when I create a list in main of type: Reteta.
After I display the list I receive am error of bad allocation. If I comment the destructor from the class Reteta the program works. Can you help me find the bug? Or maybe I didn't display the list well so the program have other problems to take care of.
Here is the code:
#include<iostream>
#include<fstream>
#include<list>
using namespace std;
class Medicament{
private:
char *denumire;
float pret;
public:
Medicament()
{
this->pret = 0;
this->denumire = new char[strlen("Fara denumire")];
strcpy(this->denumire, "Fara denumire");
}
Medicament(char* denumire, float pret)
{
this->denumire = new char[strlen(denumire) + 1];
strcpy(this->denumire, denumire);
this->pret = pret;
}
Medicament(const Medicament& x)
{
this->denumire = new char[strlen(x.denumire) + 1];
strcpy(this->denumire, x.denumire);
this->pret = x.pret;
}
~Medicament()
{
if (this->denumire)
{
delete[] this->denumire;
}
}
void setDenumire(char *x)
{
if (x)
{
if (this->denumire)
{
delete[] this->denumire;
}
this->denumire = new char[strlen(x) + 1];
strcpy(this->denumire, x);
}
}
char* getDenumire()
{
return this->denumire;
}
void setPret(float f)
{
if (f)
{
this->pret = f;
}
}
Medicament operator=(Medicament x)
{
this->denumire = new char[strlen(x.denumire) + 1];
strcpy(this->denumire, x.denumire);
this->pret = x.pret;
return *this;
}
friend ostream& operator<<(ostream& consola, Medicament &x)
{
consola << "Medicament: " << x.denumire << endl; //error here
consola << "Pret: " << x.pret << endl;
return consola;
}
float getPret()
{
return this->pret;
}
friend class Reteta;
};
class Reteta{
protected:
Medicament *medicamente;
int n;
public:
Reteta()
{
this->n = 0;
this->medicamente = NULL;
}
Reteta(Medicament *v, int n)
{
this->n = n;
this->medicamente = new Medicament[n];
for (int i = 0; i < n; i++)
{
this->medicamente[i] = v[i];
}
}
~Reteta()
{
if (this->medicamente)
{
delete[] this->medicamente; //The problem is here. If I comment this the program works.
}
}
int getN()
{
return this->n;
}
friend ostream& operator<<(ostream& consola, Reteta& x)
{
consola << "Numar de medicamente: " << x.n << endl;
consola << " -->Lista Medicamente<-- "<<endl;
for (int i = 0; i < x.n; i++)
{
consola << x.medicamente[i].getDenumire() <<endl; //error at this line when I compile
consola << x.medicamente[i].getPret()<< endl;
}
return consola;
}
void adaugaMedicament(Medicament x)
{
Reteta y;
y.medicamente= new Medicament[this->n+1];
for (int i = 0; i < this->n; i++)
{
y.medicamente[i] = this->medicamente[i];
}
y.medicamente[this->n] = x;
delete[] this->medicamente;
this->medicamente = new Medicament[this->n + 1];
this->n++;
for (int i = 0; i < this->n; i++)
{
this->medicamente[i] = y.medicamente[i];
}
}
Medicament operator[](int i)
{
if (i >= 0 && i < this->n)
{
return this->medicamente[i];
}
}
friend class RetetaCompensata;
virtual float getValoare()
{
float sum = 0;
for (int i = 0; i < this->n; i++)
{
sum=sum+this->medicamente[i].getPret();
}
return sum;
}
friend ifstream& operator>>(ifstream& consola, Reteta& x)
{
char aux[30];
float z;
consola >> x.n;
if (x.medicamente)
delete[] x.medicamente;
x.medicamente = new Medicament[x.n];
for (int i = 0; i < x.n; i++)
{
consola >> aux >> z;
Medicament m(aux, z);
x.medicamente[i] = m;
}
return consola;
}
};
class RetetaCompensata : public Reteta{
private:
float procentCompensat;
public:
RetetaCompensata(float procent)
{
this->procentCompensat = procent;
}
RetetaCompensata(Reteta r, float procent)
{
this->procentCompensat = procent;
this->n = r.n;
this->medicamente = new Medicament[r.n];
for (int i = 0; i < r.n; i++)
{
this->medicamente[i] = r.medicamente[i];
}
}
float getValoare()
{
float sum = 0;
sum = this->procentCompensat*this->getValoare();
return sum;
}
friend ostream& operator<<(ostream& consola, RetetaCompensata &x)
{
consola << "**Procent compensat: " << x.procentCompensat << endl;
consola << "Numar de medicamente: " << x.n << endl;
consola << " -->Lista Medicamente<-- " << endl;
for (int i = 0; i < x.n; i++)
{
consola << x.medicamente[i] << " ";
}
return consola;
}
};
void main()
{
//1
Medicament nurofen("Nurofen", 11.25f);
Medicament aspirina = nurofen;
aspirina.setDenumire("Aspirina");
aspirina.setPret(4.5f);
Medicament bixtonim("Bixtonim", 8.2f);
Medicament temp;
temp = nurofen;
cout << temp << endl;
cout << nurofen << endl;
cout << aspirina << endl;
//2
Medicament medicamente[] = { aspirina, nurofen };
Reteta r0(medicamente, 2);
cout << r0 << endl;
//3
Reteta r1;
r1.adaugaMedicament(nurofen);
r1.adaugaMedicament(aspirina);
for (int i = 0; i < r1.getN(); i++)
{
cout << r1[i] << endl;
}
//4
RetetaCompensata r2(0.5);
r2.adaugaMedicament(bixtonim);
r2.adaugaMedicament(aspirina);
RetetaCompensata r3(r1, 0.2);
cout << "AFISARE R3" << endl;
cout << r3 << endl << endl;
Reteta* p = &r1;
cout <<"Valoare reteta r1: "<< p->getValoare() << endl;
//5
Reteta r4;
ifstream fisier("retete.txt");
fisier >> r4;
cout << r4 << endl;
//6
cout << endl << "Afisare Lista :" << endl << endl << endl;
list<Reteta> R;
list<Reteta>::iterator it;
R.push_back(r0);
R.push_back(r1);
R.push_back(r3);
R.push_back(r2);
R.push_back(r4);
for (it = R.begin(); it != R.end(); it++)
{
cout << *it << " Valoare Reteta: " << it->getValoare() << endl << endl << endl; // error at this line when I compile
}
}

This is a memory overwrite:
this->denumire = new char[strlen("Fara denumire")];
strcpy(this->denumire, "Fara denumire");
You are not allocating room for the terminating null character:
this->denumire = new char[strlen("Fara denumire") + 1];
strcpy(this->denumire, "Fara denumire");
But why do this when you have std::string available? That alone not only alleviates errors like this, but you don't need to write assignment operators, copy constructor, or destructor for your Medicament class.
The other error is that your Reteta class lacks a copy constructor and assignment operator, thus it is not safely copyable due to the Medicament* member. You are then using this class as a type in std::list<Reteta>.
Since Reteta is not safely copyable, and std::list makes copies, you enter the world of undefined behavior. Thus you must provide appropriate copy / assignment operators for the Reteta class.

Related

C++ Memory Leak Error (definitely lost: 280 bytes in 2 blocks)

I have Memory Leak in my code and not sure how to diagnose it. There are 3 files and the main.cpp is the test file therefore cannot be altered. The program is using a Mem Checker and it displays that ==159804== Memcheck, a memory error detector, definitely lost: 280 bytes in 2 blocks.
Main.cpp (Cannot be altered)
#include<iostream>
#include<cstring>
#include"Basket.h"
#include"Basket.h" //intentional
using namespace std;
using namespace sdds;
void printHeader(const char* title)
{
char oldFill = cout.fill('-');
cout.width(40);
cout << "" << endl;
cout << "|> " << title << endl;
cout.fill('-');
cout.width(40);
cout << "" << endl;
cout.fill(oldFill);
}
int main()
{
sdds::Fruit fruits[]{
{"apple", 0.65},
{"banana", 1.25},
{"pear", 0.50},
{"mango", 0.75},
{"plum", 2.00},
};
{
printHeader("T1: Default Constructor");
Basket aBasket;
cout << aBasket;
// conversion to bool operator
if (aBasket)
cout << "Test failed: the basket should be empty!\n";
else
cout << "Test succeeded: operator said the basket is empty!\n";
cout << endl;
}
{
printHeader("T2: Custom Constructor");
Basket aBasket(fruits, 2, 6.99);
cout << aBasket;
// conversion to bool operator
if (aBasket)
cout << "Test succeeded: operator said the basket has content!\n";
else
cout << "Test failed: the basket should NOT be empty!\n";
cout << endl;
}
{
printHeader("T3: += operator");
Basket aBasket;
aBasket += fruits[2];
(aBasket += fruits[0]) += fruits[4];
aBasket.setPrice(12.234);
cout << aBasket;
cout << endl;
}
{
printHeader("T4: Copy Constructor");
Basket b1;
Basket b2(b1);
cout << "Basket #1 -> " << b1;
cout << "Basket #2 -> " << b2;
b1 += fruits[3];
b1.setPrice(3.50);
Basket b3(b1);
cout << "Basket #3 -> " << b3;
cout << endl;
}
{
printHeader("T5: Copy Assignment");
Basket b1, b2, b3(fruits, 5, 19.95);
b1 = b2;
cout << "Basket #1 -> " << b1;
cout << "Basket #2 -> " << b2;
b1 = b3;
cout << "Basket #1 -> " << b1;
b3 = b2;
cout << "Basket #3 -> " << b3;
}
return 0;
}
Basket.h
#ifndef Basket_h
#define Basket_h
#include <stdio.h>
#include <iomanip>
#include <iostream>
namespace sdds{
struct Fruit
{
char m_name[30 + 1];
double m_qty;
};
class Basket{
private:
Fruit *m_fruits;
int m_cnt;
double m_price;
public:
Basket();
Basket(Fruit* fruits, int cnt, double price);
Basket(Basket &d);
Basket& operator = (Basket &d);
~Basket();
void setPrice(double price);
operator bool() const;
Basket& operator+=(Fruit d);
friend std::ostream& operator << (std::ostream& output, Basket test);
};
}
#endif /* Basket_h */
Basket.cpp
#include "Basket.h"
using namespace sdds;
namespace sdds {
Basket::Basket(){
m_fruits = nullptr;
m_cnt = 0;
m_price = 0;
}
Basket::Basket(Fruit* fruits, int cnt, double price){
if (cnt > 0 && fruits != nullptr) {
m_cnt = cnt;
m_price = price;
m_fruits = new Fruit[cnt + 1];
for (int i = 0; i < cnt; i++) {
m_fruits[i] = fruits[i];
}
}else{
m_fruits = nullptr;
m_cnt = 0;
m_price = 0;
}
}
Basket::Basket(Basket &d){
m_price = d.m_price; // Shallow Copying
m_cnt = d.m_cnt;
m_fruits = new Fruit[m_cnt + 1];
for (int i = 0; i < m_cnt; i++) { // Deep Copying
m_fruits[i] = d.m_fruits[i];
}
}
Basket& Basket::operator = (Basket &d){
m_price = d.m_price;
m_cnt = d.m_cnt;
m_fruits = new Fruit[m_cnt + 1];
for (int i = 0; i < m_cnt; i++) {
m_fruits[i] = d.m_fruits[i];
}
return *this;
}
Basket::~Basket(){
delete [] m_fruits;
}
void Basket::setPrice(double price){
m_price = price;
}
Basket::operator bool() const {
// returning true if the Basket is valid
return m_fruits != nullptr;
}
Basket& Basket::operator+=(Fruit d){
Fruit* tmp = new Fruit[m_cnt + 1];
for (int i = 0; i < m_cnt; i++) {
tmp[i] = m_fruits[i];
}
tmp[m_cnt++] = d;
delete [] m_fruits;
m_fruits = tmp;
return *this;
}
std::ostream& operator << (std::ostream& output, Basket test){
if (test.m_cnt == 0 || test.m_price == 0 || test.m_fruits == nullptr) {
output << "The basket is empty!" << std::endl;
}else{
output << "Basket Content:" << std::endl;
std::cout << std::fixed;
std::cout << std::setprecision(2);
for (int i = 0 ; i < test.m_cnt; i++) {
output << std::setw(10) << test.m_fruits[i].m_name << ": " <<test.m_fruits[i].m_qty << "kg" << std::endl;
}
output << "Price: " << test.m_price << std::endl;
}
return output;
}
}
Your assignment operator leaks memory, since you failed to delete[] the original data when doing the assignment.
The easiest way to get a working assignment operator is to use the copy/swap idiom:
#include <algorithm>
//...
Basket& Basket::operator = (const Basket &d)
{
if ( &d != this)
{
Basket temp(d);
std::swap(temp.m_price, m_price);
std::swap(temp.m_cnt, cnt);
std::swap(temp.m_fruits, fruits);
}
return *this;
}
Your original assignment operator had multiple flaws:
Did not delete[] the old memory.
Did not do a check for self-assignment, thus Basket a; a = a; would fail.
Changed member variables before issuing a call to new[], thus an exception thrown would corrupt your object.
All three issues are taken care of with the code shown above.
In fact, item 2) need not be done for copy / swap to work (but done in the example code above, just to show what your original code was missing).

I need help using the "==" in this solution

The function contains(Object obj) returns true even though an object of that value is not in the pointer array. I have tried to overload the "==" function in my class Rec. It is using the function but the results are not what I want.
This is an attempt at a solution to a homework problem.
Design a class template, Collection, that stores a collection of Objects (in an array), along with the current size of the collection. Provide public functions isEmpty, makeEmpty, insert, remove, and contains. contains(x) returns true if and only if an Object that is equal to x is present in the collection.
I have tried other ways but I can't use nullptr as assignment.
#include "pch.h"
#include <iostream>
using namespace std;
template <typename Object>
class Collection {
public:
int ndx = 0;
Object *data[10] = { nullptr };
void insert(Object obj) {
if (ndx == 10) {
cout << "Container is full!!" << endl;
}
else {
data[ndx] = &obj;
//cout << data[ndx]->area() << endl;
++ndx;
cout << "Inserted in Location: " << ndx - 1 << endl;
}
}
void isEmpty() {
if (ndx > 0) {
cout << "Not empty " << ndx << " items!" << endl;
}
else {
cout << "Is empty, " << ndx << " items!" << endl;
}
}
void makeEmpty() {
for (int i = 0; i < ndx; i++)
data[i] = nullptr;
ndx = 0;
cout << "It is Empty!" << endl;
}
void remove(Object obj) {
cout << obj.area() << "here" << endl;
int index = -1;
for (int i = 0; i < ndx; i++) {
if (data[i] == obj) {
index = i;
}
}
if (index != -1) {
if (index == ndx - 1)
--ndx;
else {
for (int i = index; i < ndx; i++) {
data[i] = data[i + 1];
}
--ndx;
data[ndx] = nullptr;
}
cout << "Object Removed Location: " << index << endl;
}
else {
cout << "Object not found!" << endl;
}
}
bool contains(Object obj) {
for (int i = 0; i < ndx; i++) {
if (data[i] == obj) {
return true;
}
}
return false;
}
};
class Rec {
public:
int width;
int hieght;
void setValues(int &w, int &h) {
width = w;
hieght = h;
}
void setWidth(int &w) {
width = w;
}
void setHieght(int &h) {
hieght = h;
}
int area() { return width * hieght; };
bool operator==(const Rec& rhs)const {
cout << "used Normal" << endl;
return (width == rhs.width) && (hieght == rhs.hieght);
}
};
bool operator==(Rec * lhs, Rec rhs) {
cout << "used *" << endl;
return (lhs->width == rhs.width) && (lhs->hieght == rhs.hieght);
}
int main()
{
Collection<Rec> test;
for (int i = 0; i < 11; i++) {
Rec r;
r.setValues(i, i);
test.insert(r);
}
Rec r;
int i = 22;
r.setValues(i, i);
bool t = test.contains(r);
cout << "Here?: " << t << endl;
r.setValues(i, i);
test.remove(r);
test.makeEmpty();
//cout << test.data[6]->area() << endl;
return 0;
}
I want it to return false.

C++ Delete[] causing program crash [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
My program works fine while I don't have a call to delete[] buf in the destructor. However, when I include it the program crashes at the start of the output.
Here are my files.
//string.cpp
#include "String.h"
#include
#include
extern ofstream csis;
String::String() {
buf = "\0";
length = 0;
}
String::String(const char* tar) {
int temp = strlen(tar);
length = temp;
buf = new char[length + 1];
buf[length] = '\0';
for (int i = 0; i < length; i++){
buf[i] = tar[i];
}
}
String::String(char a) {
length = 1;
buf = new char[length+1];
buf[length] = '\0';
buf[0] = a;
}
String::String(int x) {
int alloc = x;
if (x < 0) {
alloc = 0;
}
buf = new char[alloc+1];
length = x;
buf[0] = '\0';
}
String::String(const String& a) {
length = a.length;
buf = new char[length+1];
for (int i = 0; i < length; i++) {
buf[i] = a.buf[i];
}
}
String::String(char a, int x) {
buf = new char[x+1];
for (int i = 0; i < x; i++) {
buf[i] = a;
}
buf[x] = '\0';
length = strlen(buf);
}
String::~String() {
delete buf;
}
String& String::operator=(const String& tar) {
buf = new char[tar.length+1];
strcpy(buf, tar.buf);
length = tar.length;
buf[length] = '\0';
return *this;
}
String& String::operator=(const char* chr) {
buf = (char*)chr;
length = int(strlen(chr));
return *this;
}
String operator+(const String& a, const String& b) {
String sum;
int size = a.length + b.length;
sum.buf = new char[size+1];
sum.length = size;
for (int i = 0; i < a.length; i++) {
sum.buf[i] = a.buf[i];
}
int j = 0;
for (int i = a.length; i < size; i++) {
sum.buf[i] = b.buf[j];
j++;
}
sum.buf[size] = '\0';
return sum;
}
String operator+(const String& tar, const char* c) {
String sum;
int size = int(strlen(c)) + tar.length;
sum.buf = new char[size+1];
sum.length = size;
for (int i = 0; i < tar.length; i++) {
sum.buf[i] = tar.buf[i];
}
int j = 0;
for (int i = tar.length; i < size; i++) {
sum.buf[i] = c[j];
j++;
}
sum.buf[size] = '\0';
return sum;
}
String operator+(const char* c, const String& tar) {
String sum;
int size = int(strlen(c)) + tar.length;
sum.buf = new char[size+1];
sum.length = size;
for (int i = 0; i < int(strlen(c)); i++) {
sum.buf[i] = c[i];
}
int j = 0;
for (int i = strlen(c); i < size; i++) {
sum.buf[i] = tar.buf[j];
j++;
}
sum.buf[size] = '\0';
return sum;
}
String operator+(const String& tar, char c) {
String sum;
int size = 1 + tar.length;
sum.buf = new char[size];
sum.length = size;
for (int i = 0; i < tar.length; i++) {
sum.buf[i] = tar.buf[i];
}
int j = 0;
for (int i = tar.length; i < size; i++) {
sum.buf[i] = c;
j++;
}
sum.buf[size] = '\0';
return sum;
}
String operator+(char c, const String& tar) {
String sum;
int size = 1 + tar.length;
sum.buf = new char[size+1];
sum.length = size;
for (int i = 0; i < 1; i++) {
sum.buf[i] = c;
}
int j = 0;
for (int i = 1; i < size; i++) {
sum.buf[i] = tar.buf[j];
j++;
}
sum.buf[size] = '\0';
return sum;
}
String& String::operator+=(const String& tar) {
String temp = *this;
temp = temp + tar;
*this = temp;
return *this;
}
String& String::operator+=(const char c) {
String temp = *this;
temp = temp + c;
*this = temp;
return *this;
}
String String::operator+() const {
String sum;
sum.length = length;
sum.buf = new char[sum.length+1];
strcpy(sum.buf, buf);
for (int i = 0; i < length; i++) {
sum.buf[i] = toupper(buf[i]);
}
sum.buf[length] = '\0';
return sum;
}
int operator==(const String & tar, const String& tar2) {
int check = 0;
if (strcmp(tar.buf, tar2.buf) == 0) {
check += 1;
}
else if (strcmp(tar.buf, tar2.buf) != 0) {
check = 0;
}
return check;
}
int operator!=(const String& tar, const String& tar2) {
int check = 0;
if (!(strcmp(tar.buf, tar2.buf) == 0)) {
check += 1;
}
else if (!(strcmp(tar.buf, tar2.buf) != 0)) {
check = 0;
}
return check;
}
int operator<(const String& a, const String& b) {
int check = 0;
if (a.length < b.length) {
check += 1;
}
return check;
}
int operator<=(const String& a, const String& b) {
int check = 0;
if (a.length <= b.length) {
check += 1;
}
return check;
}
int operator>(const String& a, const String& b) {
int check = 0;
if (a.length > b.length) {
check += 1;
}
return check;
}
int operator>=(const String& a, const String& b) {
int check = 0;
if (a.length >= b.length) {
check += 1;
}
return check;
}
char& String::operator[](int x) {
int out;
if (x >= 0 && x < length) {
out = x;
}
else if (!(x >= 0 && x < length)) {
int output = NULL;
cout << "ERROR: Invalid Index with [] operator." << endl;
csis << "ERROR: Invalid Index with [] operator." << endl;
out = NULL;
}
return buf[out];
}
char* operator+(const String& a, int x) {
return &a.buf[x];
}
char* operator+(int x, const String& a) {
return &a.buf[x];
}
String String::operator++(int val) {
String temp;
temp = *this;
for (int i = 0; i < temp.length; i++) {
temp.buf[i] = temp.buf[i] + 1;
}
return temp;
}
String String::operator--(int val) {
String temp;
temp = *this;
for (int i = 0; i < temp.length; i++) {
temp.buf[i] = temp.buf[i] - 1;
}
return temp;
}
String String::operator++() {
String temp = *this;
for (int i = 0; i < temp.length; i++) {
temp.buf[i] = (temp.buf[i] + 1);
}
return temp;
}
String String::operator--() {
String temp = *this;
for (int i = 0; i < temp.length; i++) {
temp.buf[i] = (temp.buf[i] - 1);
}
return temp;
}
int String::getLength() {
return length;
}
String String::substr(int a, int b) {
String temp = *this;
char *fill = new char[b+1];
int i = a;
int x = 0;
while (x <= b) {
fill[i] = temp.buf[i];
i++;
x++;
}
temp.buf = fill;
temp.buf[length] = '\0';
return temp;
}
void String::print() {
cout << """";
csis << """";
for (int i = 0; i < length; i++) {
cout << buf[i];
csis << buf[i];
}
cout << """";
csis << """";
cout << " Length: " << length << endl;
csis << " Length: " << length << endl;
}
ostream& operator<<(ostream& o, const String& tar) {
for (int i = 0; i < tar.length; i++) {
o << tar.buf[i];
}
return o;
}
Here is string.h
//string.h
#ifndef _STRING_H
#define _STRING_H
#include <iomanip>
#include <stdlib.h>
#include <iostream>
using namespace std;
class String {
protected:
int length;
char* buf;
public:
String();
String(const char*);
String(char a);
String(int x);
String(const String&);
String(char a, int x);
~String();
// Operator Overload
String& operator=(const String& tar);
String& operator= (const char*);
friend String operator+(const String& a, const String& b);
friend String operator+(const String&, const char*);
friend String operator+(const char* c, const String& tar);
friend String operator+(const String&, char c);
friend String operator+(char c, const String& tar);
String& operator+=(const String& tar);
String& operator+=(const char c);
String operator+() const;
friend int operator==(const String&, const String&);
friend int operator!=(const String&, const String&);
friend int operator<(const String&, const String&);
friend int operator<=(const String&, const String&);
friend int operator>(const String&, const String&);
friend int operator>=(const String&, const String&);
char& operator[](int);
friend char* operator+(const String&, int);
friend char* operator+(int, const String&);
String operator++();
String operator--();
String operator++(int);
String operator--(int);
int getLength();
String substr(int a, int b);
void print();
friend ostream& operator<<(ostream&, const String&);
};
#endif
Here is StringDriver.cpp
// StringDriver.cpp
// MATTHEW BUTNER
// ID: 011029756
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include "StringDriver.h"
using namespace std;
ofstream csis;
int main() {
csis.open("csis.txt");
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
test9();
test10();
test11();
test12();
test13();
test14();
test15();
test16();
test17();
test18();
test19();
test20();
csis.close();
}
void test1() {
cout << "1. Testing S1: String default ctor." << endl << endl;
csis << "1. Testing S1: String default ctor." << endl << endl;
String s1;
s1.print();
wait();
}
void test2() {
cout << "2. Testing S2: String one arg (char *) ctor." << endl << endl;
csis << "2. Testing S2: String one arg (char *) ctor." << endl << endl;
String s2("ABC");
s2.print();
wait();
}
void test3() {
cout << "3. Testing S3: String one arg (char) ctor." << endl << endl;
csis << "3. Testing S3: String one arg (char) ctor." << endl << endl;
String s3('Z');
s3.print();
wait();
}
void test4() {
cout << "4. Testing S4: String one arg (int) ctor." << endl << endl;
csis << "4. Testing S4: String one arg (int) ctor." << endl << endl;
String s4(10);
s4.print();
wait();
}
void test5() {
cout << "5. Testing S5, T5: String copy ctor." << endl << endl;
csis << "5. Testing S5, T5: String copy ctor." << endl << endl;
String s5("Purple Rain");
s5.print();
String t5(s5);
t5.print();
wait();
}
void test6() {
cout << "6. Testing S6: String two arg (char, int) ctor." << endl << endl;
csis << "6. Testing S6: String two arg (char, int) ctor." << endl << endl;
String s6('*', 10);
s6.print();
wait();
}
void test7() {
cout << "7. Testing S7, T7, U7: String assignment." << endl << endl;
csis << "7. Testing S7, T7, U7: String assignment." << endl << endl;
String s7("Sally Ride"), t7, u7;
t7 = u7 = s7;
s7.print();
t7.print();
u7.print();
wait();
}
void test8() {
cout << "8. Testing S8: String assignment." << endl << endl;
csis << "8. Testing S8: String assignment." << endl << endl;
String s8("ABC");
s8 = s8;
s8.print();
wait();
}
void test9() {
cout << "9. Testing S9: Implicit type conversion." << endl << endl;
csis << "9. Testing S9: Implicit type conversion." << endl << endl;
String s9;
s9 = "ABC";
s9.print();
wait();
}
void test10() {
cout << "10. Testing S10, T10, U10: String concatenation." << endl << endl;
csis << "10. Testing S10, T10, U10: String concatenation." << endl << endl;
String s10("DEF");
String t10('H');
String u10("ABC" + s10 + "G" + t10 + 'I');
u10.print();
String v10('X' + u10);
v10.print();
wait();
}
void test11() {
cout << "11. Testing S11, T11: String concatenation." << endl << endl;
csis << "11. Testing S11, T11: String concatenation." << endl << endl;
String s11('A');
String t11("BC");
s11 += s11 += t11 += 'D';
s11.print();
t11.print();
wait();
}
void test12() {
cout << "12. Testing S12, T12: String unary operator." << endl << endl;
csis << "12. Testing S12, T12: String unary operator." << endl << endl;
String s12("Unary +");
String t12(+s12);
s12.print();
t12.print();
s12 = +s12;
s12.print();
wait();
}
void test13() {
cout << "13. Testing S13, T13: String comparison operators." << endl << endl;
csis << "13. Testing S13, T13: String comparison operators." << endl << endl;
String s13("ABC"), t13("ABCD");
s13.print();
t13.print();
cout << endl;
cout << "== " << (s13 == t13 ? "True" : "False") << endl;
cout << "!= " << (s13 != t13 ? "True" : "False") << endl;
cout << "< " << (s13 < t13 ? "True" : "False") << endl;
cout << "<= " << (s13 <= t13 ? "True" : "False") << endl;
cout << "> " << (s13 > t13 ? "True" : "False") << endl;
cout << ">= " << (s13 >= t13 ? "True" : "False") << endl;
csis << endl;
csis << "== " << (s13 == t13 ? "True" : "False") << endl;
csis << "!= " << (s13 != t13 ? "True" : "False") << endl;
csis << "< " << (s13 < t13 ? "True" : "False") << endl;
csis << "<= " << (s13 <= t13 ? "True" : "False") << endl;
csis << "> " << (s13 > t13 ? "True" : "False") << endl;
csis << ">= " << (s13 >= t13 ? "True" : "False") << endl;
wait();
}
void test14() {
cout << "14. Testing S14: Overloaded subscript operator." << endl << endl;
csis << "14. Testing S14: Overloaded subscript operator." << endl << endl;
String s14("C++ is fun.");
for (int i = -1; i <= s14.getLength(); i++) {
char& ch = s14[i];
if (ch != '\0')
++ch;
}
s14.print();
wait();
}
void test15() {
cout << "15. Testing S15: Pointer notation." << endl << endl;
csis << "15. Testing S15: Pointer notation." << endl << endl;
String s15("ABCDE");
for(int i = 0; i < s15.getLength(); i++)
++(*(s15+i));
for (int j = 0; j < s15.getLength(); j++) {
cout << *(j + s15);
csis << *(j + s15);
}
cout << endl;
csis << endl;
wait();
}
void test16() {
cout << "16. Testing S16, T16, U16, V16, W16, X16, Y16, Z16: Increment and decrement operators." << endl << endl;
csis << "16. Testing S16, T16, U16, V16, W16, X16, Y16, Z16: Increment and decrement operators." << endl << endl;
String s16("ABC");
String t16(++s16);
s16.print();
t16.print();
String u16("ABC");
String v16(u16++);
u16.print();
v16.print();
String w16("ABC");
String x16(--w16);
w16.print();
x16.print();
String y16("ABC");
String z16(y16--);
y16.print();
z16.print();
wait();
}
void test17() {
cout << "17. Testing S17, T17: Substr function." << endl << endl;
csis << "17. Testing S17, T17: Substr function." << endl << endl;
String s17("All You Need Is Love"), t17;
t17 = s17.substr(4, 8);
s17.print();
t17.print();
wait();
}
void test18() {
cout << "18. Testing S18, T18: Output function." << endl << endl;
csis << "18. Testing S18, T18: Output function." << endl << endl;
String s18("Red-");
String t18("Green-");
String u18("Blue");
cout << s18 << t18 << u18;
csis << s18 << t18 << u18;
cout << endl;
csis << endl;
wait();
}
void test19() {
cout << "19. Testing S19, T19, U19: ReverseString class." << endl << endl;
csis << "19. Testing S19, T19, U19: ReverseString class." << endl << endl;
ReverseString s19("Computer");
ReverseString t19;
t19 = ~s19;
s19.print();
t19.print();
ReverseString u19(~~s19);
u19.print();
wait();
}
void test20() {
cout << "20. Testing S20, T20, U20: CaseString class." << endl << endl;
csis << "20. Testing S20, T20, U20: CaseString class." << endl << endl;
CaseString s20("BaLLooN");
CaseString t20;
t20 = s20;
s20.print();
t20.print();
CaseString u20(s20);
u20.print();
wait();
}
void wait() {
char buf;
cout << endl << "Press any key to continue." << endl;
csis << endl << endl;
cin.get(buf);
}
The problem is with the destructor in string.cpp, when I have an empty destructor, everything goes fine and well, but when I include the delete buf, it'll crash the program. Also, here are the other .h and .cpp files:
//ReverseString.h
#ifndef _REVERSESTRING_H
#define _REVERSESTRING_H
#include "String.h"
#include <iostream>
class ReverseString : public String {
public:
ReverseString();
ReverseString(const ReverseString& tar);
ReverseString(const char* c);
ReverseString& operator=(const ReverseString&);
ReverseString operator~();
};
#endif
next file,
//ReverseString.cpp
#include "ReverseString.h"
extern ostream csis;
ReverseString::ReverseString() : String() {
}
ReverseString::ReverseString(const ReverseString& tar) : String(tar) {
}
ReverseString::ReverseString(const char* c) : String(c) {
}
ReverseString& ReverseString::operator=(const ReverseString& tar) {
length = tar.length;
buf = tar.buf;
buf[length] = '\0';
return *this;
}
ReverseString ReverseString::operator~() {
ReverseString reverse;
reverse.length = length;
reverse.buf = new char[length];
int j = length - 1;
for (int i = 0; i < length; i++) {
reverse.buf[i] = buf[j];
j--;
}
return reverse;
}
CaseString.h
#ifndef _CASESTRING_H
#define _CASESTRING_H
#include "String.h"
#include <iostream>
class CaseString : public String {
protected:
char* upper;
char* lower;
public:
CaseString();
CaseString(const CaseString& tar);
CaseString(const char* c);
CaseString& operator=(const CaseString& c);
void print();
~CaseString();
};
#endif
CaseString.cpp
#include "CaseString.h"
#include <fstream>
extern ofstream csis;
CaseString::CaseString() : String() {
}
CaseString::CaseString(const CaseString& tar) : String(tar) {
upper = tar.upper;
lower = tar.lower;
buf = tar.buf;
length = tar.length;
}
CaseString::CaseString(const char* c) : String(c) {
lower = new char[int(strlen(c))];
upper = new char[int(strlen(c))];
int losize = strlen(c);
char* getLow = new char[losize];
for (int i = 0; i < losize; i++) {
getLow[i] = tolower(c[i]);
}
char* getHi = new char[losize];
for (int i = 0; i < losize; i++) {
getHi[i] = toupper(c[i]);
}
lower = getLow;
upper = getHi;
lower[losize] = '\0';
upper[losize] = '\0';
}
CaseString& CaseString::operator=(const CaseString& tar) {
if (&tar != this) {
String::operator=(tar);
buf = tar.buf;
length = tar.length;
lower = tar.lower;
upper = tar.upper;
}
return *this;
}
void CaseString::print() {
cout << "\"" << buf << "\"" << " " << "Length = " << length << " |" << "Lower = " << lower << " |" << "Upper = " << upper << endl;
csis << "\"" << buf << "\"" << " |" << "Length = " << length << " |" << "Lower = " << lower << " |" << "Upper = " << upper << endl;
}
CaseString::~CaseString() {
}
There are several issues that I see.
The main problem is that you sometimes assign a pointer to a character string to buf (your default constructor is one such place, and there is at least one other). This is a pointer you do not want to delete. You need to either always allocate memory for buf, or have some way to tell if you own the pointer and it should be deleted.
The other issue is that since you use new [], you need to use delete [] buf in your destructor.
In your copy constructor, you do not copy the nul byte at the end of the coped buffer.

Operator Overloading solution

i have made a c++ code. An MList that holds items in it. I overloaded the << operator to print the values in MList in a particular format. Here is the code:
friend ostream& operator<<(ostream &out, const MSet<V> &m)
{
string s = "";
s += "Size " + to_string(m.size_) + "\n";//out << m.size() << endl;
s += "Cap " + to_string(m.capacity_) + "\n"; //out << m.capacity() << endl;
for (int i = 0; i < m.size_; i++)
{
if (i < m.size_ - 1)
s += m.ary[i].element + ",";//out << m.ary[i].element << ",";
else
s += m.ary[i].element;
}
//cout << "String : " << s;
return out << s;
}
But it does not print correct value. It prints the size and capacity right but not the values. Instead of values, it prints some signs like heart:
You can see it prints size and capacity right but not the values. Here is the relevant code. I am executing case 2 only right now:
#include<iostream>
using std::cout; using std::endl;
using std::ostream; using std::cin; using std::boolalpha;
#include<string>
using std::string;
using namespace std;
template <class V>
struct SetElement
{
V element;
int cnt;
SetElement() = default;
SetElement(V v) : element(v){}
};
template <class V>
ostream &operator<<(ostream & o,const SetElement<V> &p)
{
return o << p.element;
}
template <class V>
class MSet
{
private:
SetElement<V> *ary;
size_t capacity_;
size_t size_;
public:
MSet(V val)
{
capacity_ = 2;
ary = new SetElement<V>[capacity_];
ary[0].element = val;
ary[0].cnt = 1;
size_ = 1;
}
SetElement<V>* find(V val)
{
SetElement<V> *found = nullptr;
bool yes = false;
for (int i = 0; i < size_ && !yes; i++)
{
if (ary[i].element == val)
{
found = &ary[i];
yes = true;
}
}
return found;
}
friend ostream& operator<<(ostream &out, const MSet<V> &m)
{
string s = "";
s += "Size " + to_string(m.size_) + "\n";//out << m.size() << endl;
s += "Cap " + to_string(m.capacity_) + "\n"; //out << m.capacity() << endl;
for (int i = 0; i < m.size_; i++)
{
if (i < m.size_ - 1)
s += m.ary[i].element + ",";//out << m.ary[i].element << ",";
else
s += m.ary[i].element;
}
//cout << "String : " << s;
return out << s;
}
};
int main(){
int test;
long l1, l2, l3;
cin >> test;
cout << boolalpha;
switch (test){
// ...
case 2: {
cin >> l1 >> l2;
MSet<long> m_l(l1);
auto p = m_l.find(l1);
if (p != nullptr)
cout << *p << endl;
else
cout << "Val:" << l1 << " not found " << endl;
p = m_l.find(l2);
if (p != nullptr)
cout << *p << endl;
else
cout << "Val:" << l2 << " not found " << endl;
//cout << "MList \n";
cout << m_l;
break;
}
// ...
}
}
You're adding the values into a temporary string, which may involve implicit conversions depending of the template type (here your numerical values were converted into characters).
Just print the values, without the temporary string:
friend ostream& operator<<(ostream &out, const MSet<V> &m)
{
out << "Size " << m.size_ << endl;
out << "Cap " << m.capacity_ << endl;
for (int i = 0; i < m.size_; i++)
{
if (i < m.size_ - 1)
out << m.ary[i].element << ",";
else
out << m.ary[i].element;
}
return out;
}

Constructor with a array type of another class

This is the photo of the model I have to resolve:
I have this class:
#include<iostream>
#include<fstream>
using namespace std;
class Word
{
protected:
char *value;
char type[20];
int noChars;
static int noWords;
public:
Word(char *value, char *type)
{
this->noChars = 0;
this->value = new char[strlen(value) + 1];
strcpy(this->value, value);
strcpy(this->type, type);
Word::noWords++;
}
Word()
{
this->noChars = NULL;
this->value = NULL;
strcpy(this->type,"Nedeterminat");
}
void operator=(Word &x)
{
this->noChars = x.noChars;
strcpy(this->type, x.type);
this->value = new char[strlen(x.value) + 1];
strcpy(this->value, x.value);
}
Word(const Word& x){
this->noChars = x.noChars;
strcpy(this->type, x.type);
this->value = new char[strlen(x.value) + 1];
strcpy(this->value, x.value);
}
char* getValue()
{
return this->value;
}
void setType(char* x)
{
if (x == NULL)
{
throw new exception("Tip gresit!");
}
else
{
strcpy(this->type, x);
}
}
char &operator[](int i)
{
if (i >= 0 && i <= (strlen(this->value) - 1))
{
return this->value[i];
}
else
cout << endl << "Eroare indice: " << i;
}
static int getNoWords()
{
return Word::noWords;
}
operator int()
{
return this->noChars;
}
friend ostream& operator<<(ostream&, Word&);
friend istream& operator>>(istream&, Word&);
};
ostream& operator<<(ostream& consola, Word& x)
{
consola << "Value: " << x.getValue() << endl;
consola << "Type: " << x.type << endl;
consola << "NoChars: " << x.noChars << endl;
return consola;
}
istream& operator>>(istream& consola, Word& x){
cout << "Value: "; consola >> x.value;
cout << "Type: "; consola >> x.type;
cout << "NoChars: "; consola >> x.noChars;
return consola;
}
int Word::noWords = 0;
class Dictionary{
private:
char *language;
int noWords;
bool isOnline;
Word v[100];
public:
Dictionary(char *language, Word w, int noWords, bool isOnline)
{
this->language = new char[strlen(language) + 1];
strcpy(this->language, language);
for (int i = 0; i < 100; i++)
{
this->v[i] = w;
}
this->noWords = noWords;
this->isOnline = isOnline;
}
};
int main()
{
//1
Word w1("exam", "noun");
/*Word w2;*/
Word w3 = w1;
cout << w3;
//2
cout << endl << "Word value: " << w3.getValue();
Word w2("to take", "noun");
w2.setType("verb");
//3
w3 = w2;
cout << endl << w3;
Word *pw = new Word("pointer", "noun");
delete pw;
//4
cin >> w3; cout << w3;
char character = w3[2];
cout << endl << character;
//5
double noChars = (int)w1;
cout << endl << noChars;
cout << endl << Word::getNoWords() << endl;
//6
Dictionary dictionary1("English", NULL, 0, false);
}
I have this main:
Dictionary dictionary1("English", NULL, 0, false);
How should I change the constructor to work? I receive a error :
Arrgument types are:(const char[8],int,int,bool);
And how should I write the default constructor?
NULL cannot be assigned to Word. Try Word() instead which will call the default constructor to Word. Consider changing that function parameter to const Word& - anonymous temporaries are allowed to bind to const references.
I'd prefer to see a std::string as the type for the member variable language; using a const std::string& as the function parameter. Then you will not have to worry about a subsequent delete call, and defining your own assignment operators and copy constructors. Currently, your class leaks memory.
You can not Assign null to the type Word. If you want to default it you should pass something like word()
Dictionary dictionary1("English", word(), 0, false);
EDIT:
The better approach,IMO, that will work for the same main() you have is like this:
class Dictionary{
private:
std::string language;
int noWords;
bool isOnline;
std::array<Word,100> v;
public:
Dictionary(std::string const& language, Word* w, int noWords, bool isOnline): language (language),isOnline(isOnline ),noWords(noWords)
{
for (int i = 0; i < 100; i++){
this->v[i] = (w==NULL)?word():*w;
}
}
};