I have an array of pointers that point to Building objects that look like this:
class Building {
int id ;
int year;
double price;
char* adress;
};
What I'm trying to do is to remove objects from the array via the id using operator-, but I don't really know how to do so. My list class looks like this:
class List {
Building* buildingList[10];
static int buildingNr;
public:
List operator-(int id) {
bool exists = false;
int index;
for(int i = 0; i < buildingNr; i++)
if (buildingList[i]->getId() == id) {
exists = true;
index = i;
cout << "Building " << index << " was deleted." << endl;
}
if (exists) {
delete buildingList[index];
buildingList[index] = buildingList[buildingNr];
buildingList[buildingNr] = NULL;
buildingNr--;
}
else throw - 1;
}
};
int List::buildingNr = 0;
I know that there are far easier ways of doing this, like using std::vector, but this is an assignment and I have to do it using the overloaded operator- and an array of pointers, and the Building class has to look like that.
I also have the operator+ which adds an element to the array, and that works fine.
Your operator- is not implemented correctly. Although its loop to find an object is fine, removing that object is broken. You are not updating the array correctly, as you need to shift down ALL of the array elements after the found index, which you are not doing.
Also, make sure your List class implements the Rule of 3/5/0 correctly. The return value of operator- is supposed to return a new List object, so a copy has to be made. You should not be modifying the this object at all in operator- (that is the job of operator-= to do; see What are the basic rules and idioms for operator overloading?).
Also, the buildingNr member should not be static. That prevents you from using multiple List objects at a time.
Try something more like this instead:
#include <algorithm>
class List {
Building* buildingList[10];
int buildingNr;
public:
List() : buildingNr(0) {}
List(const List &src) : buildingNr(src.buildingNr) {
for(int i = 0; i < buildingNr; ++i) {
buildingList[i] = new Building;
buildingList[i]->id = src.buildingList[i]->id;
buildingList[i]->year = src.buildingList[i]->year;
buildingList[i]->price = src.buildingList[i]->price;
buildingList[i]->adress = new char[strlen(src.buildingList[i]->adress)+1);
strcpy(buildingList[i]->adress, src.buildingList[i]->adress);
}
}
~List() {
for(int i = 0; i < buildingNr; ++i) {
delete[] buildingList[i]->adress;
delete buildingList[i];
}
}
List& operator=(const List &rhs) {
if (this != &rhs) {
List tmp(rhs);
std::swap_ranges(buildingList, buildingList+10, tmp.buildingList);
std::swap(buildingNr, tmp.buildingNr);
}
return *this;
}
List& operator-=(int id) {
for(int i = 0; i < buildingNr; ++i) {
if (buildingList[i]->getId() == id) {
delete buildingList[i];
for(int j = i + 1; j < buildingNr; ++j) {
buildingList[j - 1] = buildingList[j];
}
buildingList[buildingNr] = NULL;
--buildingNr;
cout << "Building " << i << " was deleted." << endl;
return *this;
}
}
throw -1;
}
...
};
friend List operator-(List lhs, int id) {
lhs -= id;
return lhs;
}
Related
I am required to implement a dynamic array that adjusts, dynamically, in accordance with the number of value (temperatures) that are input into the code. I have written the majority of the code for this to be possible, however I have run into a bug and for the life of me, have been unable to locate the issue.
The program is supposed to output the values of temp_a, make temp_b = temp_a, output the value of temp_b, and then clear the value of temp_a, and finally output the values of temp_b once more.
However, when I compile the program, it outputs that the list is full and cannot add any more values, meaning there is a logic error somewhere in the code.
Please forgive me for the lengthy code, as soon as I can locate the error, the code shall be separated into multiple compilations.
#include <iostream>
using namespace std;
class TemperatureList {
private:
int* temp; // pointer to dynamic array
short current_size; // current number of elements
short max_size; // max number of elements allowed in this list
public:
// Overloading assignment operator
void operator =(const TemperatureList& another_list);
// === Constructors ===
// Default constructor
TemperatureList();
// Constructor that accepts an integer parameter that specifies the max length of the list
TemperatureList(int max);
// Copy constructor that accepts another List as parameter
TemperatureList(const TemperatureList& another_list);
// Destructor
~TemperatureList();
// === Modifier functions ===
// add new_value to end of list if there is still space
void add_temperature(int new_value);
// === Accessor functions ===
// return current current_size of the list
short get_current_size();
// === Other functions ===
// return the last element, or 0 if the list is empty, with a warning output
int get_last();
// return element at the position-th position, or 0 if the list is empty, with a warning output
int get_temp(short position);
// returns if current_size == 0
bool set_temp(short position, int value);
// returns if current_size == 0
bool empty();
// returns if current_size == max_size
bool full();
// Output list separated by commas
friend ostream& operator <<(ostream& outs, const TemperatureList& list);
};
int main() {
TemperatureList temp_a;
temp_a.add_temperature(23.5);
temp_a.add_temperature(24.6);
cout << temp_a;
TemperatureList temp_b = temp_a;
cout << temp_b;
temp_a = TemperatureList();
cout << "Now there's no temperatures in a.\n";
cout << temp_a;
cout << "How about temperatures in b?\n";
cout << temp_b;
return 0;
}
void TemperatureList::operator =(const TemperatureList& another_list) {
delete[] temp;
current_size = another_list.current_size;
max_size = another_list.max_size;
if (current_size > 0) {
temp = new int[max_size];
for (int i = 0; i < max_size; i++) {
temp[i] = another_list.temp[i];
}
}
else {
temp = NULL;
}
}
TemperatureList::TemperatureList() {
current_size = 0;
max_size = 0;
temp = NULL;
}
TemperatureList::TemperatureList(int max) : max_size(max) {
current_size = 0;
temp = new int[max];
}
TemperatureList::TemperatureList(const TemperatureList& another_list) {
current_size = another_list.current_size;
max_size = another_list.max_size;
if (current_size > 0) {
temp = new int[max_size];
for (int i = 0; i < max_size; i++) {
temp[i] = another_list.temp[i];
}
}
else {
temp = NULL;
}
}
TemperatureList::~TemperatureList() {
//cout << "== I am in destructor ==\n";
delete[] temp;
}
void TemperatureList::add_temperature(int new_value) {
if (current_size < max_size) {
temp[current_size] = new_value;
current_size++;
}
else {
cout << "Cannot add value to the list. It is full.\n";
}
}
int TemperatureList::get_last() {
if (empty()) {
cout << "The list is empty\n";
return 0;
}
else {
return temp[current_size - 1];
}
}
int TemperatureList::get_temp(short position) {
if (current_size >= position) {
return temp[position - 1];
}
else {
cout << "There is no temperature\n";
return 0;
}
}
bool TemperatureList::set_temp(short position, int value) {
if (current_size >= position) {
temp[position - 1] = value;
return true;
}
else {
return false;
}
}
short TemperatureList::get_current_size() {
return current_size;
}
bool TemperatureList::empty() {
return (current_size == 0);
}
bool TemperatureList::full() {
return (current_size == max_size);
}
ostream& operator <<(ostream& outs, const TemperatureList& list) {
int i;
for (i = 0; i < (list.current_size - 1); i++) {
outs << list.temp[i] << ",";
}
outs << list.temp[i];
return outs;
}
The logic error seems to stem from the fact that you initialize your current_size and max_size to zero. So, unless your run the overloaded constructor (wherein you’re set the max_size), every call to addTemperature() is going to fail the (current_size < max_size) check because they are both equal to zero.
The goal I set to myself is to overload operator+ (adding class objects). It turns out that this sum can be just interpreted as the sum of two vectors. But when it comes to the method operator+, I find it difficult to return the object. I've read similar topics and even try to apply some sugestions but with no success, unfortunatelly. I enclose some of my code.
template<class Y>
class myVect {
public:
myVect(int n = 1);
~myVect();
myVect(const myVect& a);
myVect& operator= (const myVect&);
myVect& operator+ (const myVect&);
void display(const myVect& a);
private:
int size;
Y* data;
template<class U> friend class myClass;
};
template<class Y> // constructor
myVect<Y>::myVect(int n) {
size = n;
data = new Y[size];
cout << endl << "Pass the elements" << " " << size << "\n";
for (int i = 0; i < size; i++) {
cin >> *(data + i);
}
}
template <class Y> // deconstructor
myVect<Y> :: ~myVect() {
delete[] data;
}
template<class Y> // copy constructor
myVect<Y> ::myVect(const myVect & a) {
size = a.size;
data = new Y[size];
for (int i = 0; i < size; i++) {
*(data + i) = *(a.data + i);
}
}
template<class Y> //ASSIGMENT OPERATOR
myVect<Y> & myVect<Y> :: operator= (const myVect<Y> & a) {
if (this != &a) {
delete[] data;
size = a.size;
data = new Y[size];
for (int i = 0; i < size; i++) {
*(data + i) = *(a.data + i);
}
}
return *this;
}
The method operator+ is a follows:
template<class Y>
myVect<Y>& myVect<Y> ::operator+ (const myVect<Y>& a) {
if (this->size != a.size) {
cout << endl << "not able to perform that operation - wrong dimensions" << endl;
}
else {
myVect<Y> newObj(this->size);
for (int i = 0; i < this->size; i++) {
*(newObj.data + i) = *(this->data + i) + *(a.data + i);
}
}
return newObj;
}
The error I get is 'newObj': identifier not found. I believe it's due to deconstructor. I tried to put the class myVect into a new class (encapsulate it) and contruct the return method but it didn't change antything - the type of the error is still the same. Do you know how to solve this problem?
Anyway, if it is the destructor fault, does that mean that newObj is deleted before its return?
The problem can be reduced to this:
int foo()
{
if (true) // In reality, some meaningful condition
{
int x = 4;
}
return x;
}
The variable is scoped to the if block. It doesn't exist outside of it.
You'll have to move its declaration out of the conditional, and do whatever else is required to make that work… or return from inside the condition, and do something else (throw an exception?) otherwise.
For example, given the above demonstration:
int foo()
{
int x = 0; // Or some other value
if (true) // In reality, some meaningful condition
{
x = 4;
}
return x;
}
or:
int foo()
{
if (true) // In reality, some meaningful condition
{
int x = 4;
return x;
}
throw std::runtime_error("For some reason I have no value to give you!");
}
Your next problem will be that you are trying to return a local variable by reference. You cannot do that. Return it by value instead, which is anyway idiomatic for what you're doing.
You've declared your object inside of a block, so it won't exist in the outside scope. This would normally free you up to reuse variable names across different branches; try making a newObj inside the if part of the statement and watch it not throw an error, for example.
I'm creating a dynamic array class and I'm new to c++. I'm having trouble overloading the addition operator to add a string to an object. When I do try to add a string, nothing shows up on the compile screen. I also added my copy constructor, destructor, overloaded assignment operator, and overloaded ostream operator just in case any of those were the issue. Thank you so much for the help!!
DynamicStringArray::~DynamicStringArray()
{
delete[] dynamic_Array;
dynamic_Array = NULL;
}
DynamicStringArray::DynamicStringArray(const DynamicStringArray& first)
{
size = first.returns_Size();
dynamic_Array = new string[size];
for (int n = 0; n < size; n++)
{
dynamic_Array[n] = first.get_Entry(n);
}
}
void DynamicStringArray::operator =(const DynamicStringArray& first)
{
this->size = first.returns_Size();
this->dynamic_Array = new string[size];
for (int i = 0; i < this->size; i++)
{
this->dynamic_Array[i] = first.get_Entry(i);
}
}
ostream& operator <<(ostream& out, const DynamicStringArray& first) //nonmember requires 2 arguments
{
for (int i = 0; i < first.size; i++)
{
out << first.dynamic_Array[i] << endl;
}
return out;
}
void DynamicStringArray::add_Entry(string a)
{
string* Temp_Array = dynamic_Array; //old array
dynamic_Array = new string[size + 1]; //new array
for (int i= 0; i < size; i++) //copy old string values to temp array
{
dynamic_Array[i] = Temp_Array[i];
}
dynamic_Array[size] = a; //puts string a into last position of new array
delete[]Temp_Array; //free memory space
size++;
}
DynamicStringArray DynamicStringArray::operator +(const string& a)
{
DynamicStringArray added;
added.add_Entry(a);
return added;
}
int main()
{
DynamicStringArray fav_Foods;
fav_Foods.add_Entry("pasta");
fav_Foods.add_Entry("sushi");
fav_Foods + "Burgers";
cout << fav_Foods << endl;
}
DynamicStringArray DynamicStringArray::operator +(const string& a)
{
DynamicStringArray added;
added.add_Entry(a);
return added;
}
Why do you think you need to create a new DynamicStringArray added?
Simply call add_Entry(a) on the current instance. Also, operator+() should return a reference to the instance it is called upon:
DynamicStringArray& DynamicStringArray::operator+(string const &a)
{
add_Entry(a);
return *this;
}
template <typename Object>
class Vector1 {
public:
explicit Vector1(const Object & value = Object()) : size_{0} {
array_ = new Object{value};
size_++;
}
Vector1(const Vector1 & rhs) : size_{rhs.size_} { //copy constructor
array_ = new Object[size_];
for (int i = 0; i < size_; i++) {
array_[i] = rhs.array_[i];
}
}
Vector1 & operator=(const Vector1 & rhs) { //copy assignment operator
array_ = new Object[rhs.size_];
if (this != &rhs) {
size_ = rhs.size_;
for (int i = 0; i < size_; i++) {
array_[i] = rhs.array_[i];
}
}
return *this;
}
Vector1(Vector1 && rhs) : array_{rhs.array_}, size_{rhs.size_} { //move constructor
rhs.array_ = nullptr;
rhs.size_ = 0;
}
Vector1 & operator=(Vector1 && rhs) { //move assignment operator
if (this != &rhs) {
std::swap(size_, rhs.size_);
std::swap(array_, rhs.array_);
}
return *this;
}
void print(ostream & out) const {
for (int i = 0; i < size_; i++) {
out << array_[i] << " ";
}
}
void ReadVector1() {
int count = 0;
cout << "Enter a size: ";
cin >> size_;
array_ = new Object[size_];
for (int i = 0; i < size_; i++) {
cout << "Enter element " << count + 1 << ": ";
cin >> array_[i];
count++;
}
}
size_t Size() const {
return size_;
}
**Vector1 operator+=(Vector1 & rhs) {
size_t combosize = size_ + rhs.size_;
Object combo[combosize];
int count = 0, rhscount = 0;
for (int i = 0; i < combosize; i++) {
if (i % 2 == 0) {
combo[i] = array_[count];
count++;
}
else {
combo[i] = rhs.array_[rhscount];
rhscount++;
}
}
std::swap(combosize, rhs.size_);
std::swap(combo, rhs.array_);
return *this;
}
Vector1 operator+(const Vector1 & rhs) const {
Vector1 temp(*this);
temp += rhs;
return temp;
}**
~Vector1() { //destructor
delete[] array_;
}
private:
size_t size_;
Object *array_;
};
template <typename Object>
ostream & operator<<(ostream & out, const Vector1<Object> & rhs) {
rhs.print(out);
return out;
}
int main(int argc, char **argv) {
Vector1<string> a, b;
a.ReadVector1(); //user provides input for Vector1 a
cout << a << endl;
b.ReadVector1(); //user provides input for Vector1 b
cout << b << endl;
cout << a + b << endl; //concatenates the two Vector1s
Vector1<string> d = a + b;
cout << d;
return 0;
}
The above is my code (thus far). What I'm trying to accomplish is to concatenate a's dynamic array with b's dynamic array (I cannot use vectors or any STLs, this is meant to be a rudimentary imitation of a vector).
Example:
The user inputs a size of 2 for a and inputs "Hello" and "World".
The user inputs a size of 2 for b and inputs "Goodbye" and "World".
The output should be "Hello World Goodbye World".
I highlighted what I think the problem is, which is the overloading of + and the += operators. My reasoning is that I create a new array, fill it up with the value's from a and b, swap the values, and then return the supposed concatenation.
My reasoning may not seem sound because frankly, I'm quite confused on how to proceed with this.
There are a few issues with your code concerning operator +=.
First, operator += should return a reference to the current object, i.e. return *this;. It shouldn't return a brand new Vector1 object.
Second, this line:
size_t combosize = size_ + rhs.size_;
Object combo[combosize];
is not valid ANSI C++, since arrays must be declared with a compile-time expression to denote the number of entries. Since combosize is a runtime value, it cannot be used.
You are probably using the GCC compiler, where there is a Variable Length Array extension, but again, this is an extension and is not really part of the C++ language.
Also, you are missing some constructors that would make writing operator += much easier. The constructor for Vector1 that you're lacking is this one:
Vector1::Vector1(size_t num) : array_(new Object[num]), size_(num) {}
This constructor just constructs a Vector1 with num entries.
Given the above, to fix the issues:
Vector1& operator+=(const Vector1 & rhs)
{
// create a temporary vector
Vector1 temp(size_ + rhs.size_);
// copy elements to temp array
for (int i = 0; i < size_; i++)
temp.array_[i] = array_[i];
// copy elements from rhs to temp array
int j = 0;
for (int i = size_; i < size_ + rhs.size_; i++, j++)
temp.array_[i] = rhs.array_[j];
// assign and return
*this = temp;
return *this;
}
Vector1 operator+(const Vector1 & rhs) const
{
Vector1 temp(*this);
temp += rhs;
return temp;
}
Note that in operator += we just create a temporary Vector1, fill it up with the values from *this and the passed in Vector1, and assign it to the current object. The *this = temp; line requires a working assignment operator. See the next section below.
The other issue is your Vector1::operator= is incorrect. It does not deallocate the memory allocated to _array previously, thus you have a memory leak.
The easiest way to fix this is to use the copy / swap you used in the operator=(Vector1 &&):
Vector1 & operator=(const Vector1 & rhs)
{
Vector1 temp(rhs);
std::swap(size_, temp.size_);
std::swap(array_, temp.array_);
return *this;
}
After really hard search for answers...
I tried fo(u)r hours to get and set values to an array with Overloading the subscript operator “[ ]” but can't figure out why it won't work.
What I'm tring to do here is to set someType value to an array member (On Main "darr1[i] = i*10.0" for example) with overloading the [] and with overloading the = and to get someType value from an array member (On Main "<< darr1[i] << endl" for example) but can't figure out why just the overloading of: "Type & operator [] (int index)" is invoking.
My program doesn't get to the '=' overloading or to the second '[]' overloading at all..
here is my program (sorry for the long one):
#include <iostream>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class AO1Array
{
private:
int _size;
protected:
int top;
int *B;
int *C;
AO1Array(int n);
~AO1Array();
bool isRealValue(int index)
{
if ((0 <= B[index] && B[index] < top) && (index == C[B[index]]))
return true;
return false;
};
};
AO1Array::AO1Array(int n)
{
_size = n;
top = 0;
B = new int[n];
C = new int[n];
}
AO1Array::~AO1Array()
{
delete[] B;
B = NULL;
delete[] C;
C = NULL;
}
template<class Type>
class GenericO1Array : AO1Array
{
public:
GenericO1Array(int size, Type initVal) : AO1Array(size)
{
_initVal = initVal;
Len = size;
A = new Type[size];
}
~GenericO1Array()
{
delete[] A;
A = NULL;
}
int Length() { return Len; }
Type & operator [](int index) const
{
if (AO1Array::isRealValue(index))
return A[index];
return _initVal;
}
Type & operator [] (int index)
{
if (AO1Array::isRealValue(index))
realValue = true;
else
realValue = false;
return A[index];
}
Type operator =(Type value)
{
if (realValue)
A[lastIndex] = _initVal;
else
{
AO1Array::C[top] = lastIndex;
AO1Array::B[lastIndex] = AO1Array::top++;
A[index] = value;
}
return *this;
}
private:
int Len;
int lastIndex;
bool realValue;
Type _initVal;
Type *A;
};
int main()
{
int n = 20;
GenericO1Array<double> darr1(n, 1.1);
GenericO1Array<long> iarr1(n, 2);
int i;
cout << "\nLength.darr1 = " << darr1.Length() << endl;
cout << "\nLength.iarr1 = " << iarr1.Length() << endl;
for (i = 0; i < n; i += 2)
{
darr1[i] = i*10.0;
iarr1[i] = i * 100;
} // for
cout << "\ndarr1 = " << endl;
for (i = 0; i < n; i++)
cout << "darr1[" << i << "] = " << darr1[i] << endl;
cout << "\niarr1 = " << endl;
for (i = 0; i < n; i++)
cout << "iarr1[" << i << "] = " << iarr1[i] << endl;
} // main
My program doesn't get to the '=' overloading
You are overloading the = assignment operator of Generic01Array itself, but nothing in your code is actually assigning values to your darr1 or iarr1 variables directly (there are no darr1 = ... or iarr = ... statements). That is why your = operator is not being invoked.
If you want something to happen when the user assigns a value to an element of your array, you need to create a proxy class and overload its = assignment operator, then have your [] operator return an instance of that proxy:
template<class Type>
class GenericO1Array : AO1Array
{
public:
class Proxy;
friend Proxy;
class Proxy
{
private:
Generic01Array& _arr;
int _index;
public:
Proxy(Generic01Array &arr, int index) : _arr(arr), _index(index) {}
operator Type() const
{
if (_arr.isRealValue(index))
_arr.realValue = true;
else
_arr.realValue = false;
return _arr.A[_index];
}
Proxy& operator=(const Type &value)
{
if (_arr.realValue)
_arr.A[_arr.lastindex] = _arr._initVal;
else
{
_arr.C[_arr.top] = _arr.lastIndex;
_arr.B[_arr.lastIndex] = _arr.top++;
_arr.A[_index] = value;
}
return *this;
}
};
...
Proxy operator [] (int index)
{
return Proxy(*this, index);
}
...
};
or to the second '[]' overloading at all..
You have two overloads of the [] operator, one that is const and the other is not. The const version of [] is breaking the const-ness of the operator by returning a non-const reference to the array's internal data. It should be returning a non-reference const value instead:
const Type operator [](int index) const
The non-const version of the [] operator can return a reference:
Type& operator [](int index)
You are not calling the [] operator on any const instances of your Generic01Array class, so only the non-const version of your [] operator should be getting invoked.