Assignment in Const C++ functions -
i have assignment in have write simple class. class must hold array of strings, , contain overload of '+' operator, combines elements of 2 arrays new array , returns it.
additionally, function must 'const', ran problems. when trying change class "size" attribute , array holding, errors. error when trying return object. understand cause first 2 errors because have declared function 'const', question is, proper way reassign these values inside of const method?
don't tear me bad, i've begun learning c++, , concepts bit new me. i've tried researching subject, haven't found useful answers. being said, need function working, appreciated.
here class:
class firstclass{ private: string* slist; unsigned int _size; public: firstclass(const unsigned int initsize = 1); // copy, assignment, , 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 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 } return *this; // or }
edit: quick response, , clearing doing. here 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; }
an addition operator should return new object, not reference 1 of operands. doesn't make sense a+b
modify a
or b
, or return reference 1 of them.
with in mind, easy see how operator can const.
firstclass operator+(const firstclass& rhs) const;
you implement mutating operator+=
, , implement operator+
in terms of that:
firstclass& operator+=(const firstclass& rhs); firstclass operator+(const firstclass& rhs) const { firstclass ret = rhs; ret += *this; return ret; }
or non-member:
firstclass operator+(const firstclass& lhs, const firstclass& rhs) { firstclass ret = lhs; ret += rhs; return ret; }