I have an assignment in which I have to write a simple class. This class must hold an array of strings, and contain an overload of the '+' operator, which combines the elements of two arrays into a new array and returns it.
Additionally, this function must be 'const', which is where I ran into problems. When trying to change the class "size" attribute and the array it is holding, I get errors. I also get an error when trying to return the object. I understand the cause for the first two errors is because I have declared the function 'const', but my question is, what is the proper way to reassign these values inside of a const method?
Don't tear into me too bad, I've just begun learning C++, and the concepts are a bit new to me. I've tried researching the subject, but I haven't found any useful answers. That being said, I really need to get this function working, so any help will be much appreciated.
Here is the class:
class FirstClass{
private:
string* sList;
unsigned int _size;
public:
FirstClass(const unsigned int initSize = 1);
// copy, assignment, and destructor
FirstClass& operator+(const FirstClass& add)const;
};
FirstClass::FirstClass(const unsigned int initSize):_size(initSize)
{
sList = new string[initSize];
return;
}
FirstClass& FirstClass::operator+(const FirstClass& add)
const{
if(add.sList){
int prevSize = this->_size;
this->_size += add._size; // can't do this
string newList[this->_size];
for(int a=0; a<prevSize; a++){
newList[a] = this->sList[a];
}
for(int b=0; b<add._size; b++){
sList[b+prevSize] = add.sList[b];
}
delete [] sList;
this->sList = newList; // or this
}
return *this; // or this
}
EDIT: Thanks for the quick response, and clearing up what I was doing. Here is my revised code.
FirstClass FirstClass::operator+(const FirstClass& add)
const{
FirstClass ma(this->_size + add._size);
if(add.sList){
for(int a=0; a<this->_size; a++){
ma.sList[a] = this->sList[a];
}
for(int b=0; b<add._size; b++){
ma.sList[b+this->_size] = add.sList[b];
}
}
return ma;
}
int a; int b; int c = a + b;doesaorbget modified?