I am trying to overload operators '+' and '=' for a customized class operating over files. The operator '+' overload appends the content of right operand file to left operand file. And operator '=' overload writes the contents of right operand file into left operand file. The operator overloads work fine independently but when combined in an expression they do not give expected results. With the expression in below program efile3 = (efile2+efile1) results in efile3 getting contents of only efile2's contents prior to appending. The efile2 is properly appended with efile1's content. Why the expression fails to give expected results? Does it have something to do with operator precedence?
#include<fstream>
#include<string>
class EasyFile{
std::string fileContent;
std::string temp1,temp;
char* filePath;
public:
EasyFile(char* filePath){
this->filePath = filePath;
std::ifstream file(filePath);
int count=0;
while(file){
getline(file,temp1);
count++;
}
count--;
std::ifstream file1(filePath);
while(count!=0){
getline(file1,temp1);
temp = temp + temp1+"\n";
count--;
}
setFileContent(temp);
}
void setFileContent(std::string line){
fileContent = line;
}
char* getFilePath(){
return filePath;
}
std::string getFileContent(){
return fileContent;
}
void setContent(std::string content){
std::ofstream file(filePath);
file<<content;
}
void operator=(EasyFile f);
EasyFile operator+(EasyFile f);
};
void EasyFile::operator=(EasyFile f){
this->setContent(f.getFileContent());
}
EasyFile EasyFile::operator+(EasyFile f){
EasyFile f1(this->getFilePath());
std::string totalContent = f1.getFileContent()+f.getFileContent();
f1.setContent(totalContent);
return f1;
}
int main(int argc,char** argv)
{
EasyFile efile1(argv[1]);
EasyFile efile2(argv[2]);
EasyFile efile3(argv[3]);
efile3 =(efile2+efile1);
return 0;
}