I've been having a hard time understanding classes but i've got it mostly down(atleast I think) well below in the code I overloaded the + operator for my class called clr which uses strings, my problem is on lines 59 and 61(strcpy_s(tmp,len,other.buffer);)
when I strcpy to tmp the word is copied but is then overwritten and whichever word is copied last with strcpy is the one that is returned. I tried fixing it but I am frustrated and dont know what else to do, I feel like something else might be wrong. I added couts at different points in my futile attempt to pin-point the problem but I am as stuck as a glued piece of paper.
#include <iostream>
#include <cstring>
class clr
{
private:
size_t length;
char* buffer;
public:
clr(const char* p = nullptr);
clr(const clr& other);
clr& operator=(const clr& copy);
clr operator+(const clr& copy);
void print();
~clr();
};
clr::clr(const char* p) : length(0),buffer(nullptr)
{
if(p != nullptr)
{
length = strlen(p);
if(length>0)
{
buffer = new char[length+1];
strcpy_s(buffer, length+1,p);
}
}
}
clr::clr(const clr& other)
{
length = other.length;
buffer = new char[length+1];
strcpy_s(buffer,length+1,other.buffer);
}
clr& clr::operator=(const clr& copy)
{
if((©) != this)
{
length = copy.length;
delete[] buffer;
buffer = new char[length+1];
strcpy_s(buffer,length+1,copy.buffer);
}
return *this;
}
clr clr::operator+(const clr& other)
{
size_t len = (this->length + other.length)+1;
char* tmp = new char[len];
std::cout<<strlen(tmp)<<"\n";
strcpy_s(tmp,len,other.buffer);
std::cout<<tmp<<"\n";
strcpy_s(tmp,len,buffer);
std::cout<<tmp;
std::cout<<"\n .buffer "<<other.buffer;
std::cout<<"\n buffer "<<buffer;
return clr(tmp);
}
clr::~clr()
{
delete [] buffer;
}
void clr::print()
{
std::cout<<"\n"<<buffer<<"\n";
}
int main()
{
std::cout<<"String Class\n";
clr one = "one ";
clr two = "two";
clr three = (one + two);
std::cout<<"\n\n";
three.print();
system("pause");
return 0;
}