Operator overloading

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
class MyString
{
    public:
    MyString();
    MyString(const string);
    int length();
    MyString operator=(const MyString& arg);
    MyString operator+(const MyString& arg);
    string buf;
};
MyString::MyString()
{
    buf="";
}
MyString::MyString(const string temp)
{
    buf=temp;
}
int MyString::length()
{
    return buf.length();
}
MyString MyString::operator=(const MyString& arg)
{
    buf =arg.buf;
    return *this;
}
MyString MyString::operator+(const MyString& arg)
{
    string argBuf,resultBuf;
    argBuf=arg.buf;
    resultBuf="";
    int length1=0,length2=0,first=0,second=0,count=0;
    length1=buf.length();
    length2=argBuf.length();
    while((first<length1) && (second <length2))
    {
        resultBuf[count++]=buf[first++];
        resultBuf[count++]=argBuf[second++];
    }
    resultBuf[count]='\0';
    return MyString(resultBuf);
}
int main()
{
    MyString str("Hello how are you"),str1("Hello how are you"),str3;
    str3= str+str1;
    cout<<str3.buf<<"   done";
    return 0;
}


Output should be HHeelllloo hhooww aarree yyoouu
But str2.buf isempty ..kindly solve this issue
This code

while((first<length1) && (second <length2))
{
resultBuf[count++]=buf[first++];
resultBuf[count++]=argBuf[second++];
}


is invalid because you may not use the subscript operator for an ampty sttring.

Also this statement

resultBuf[count]='\0';

is not needed for strings.

It is also unclear how does the operator + work if the srings have unequal lengths?
When I ran this in the debugger, I got an access violation after a few iterations in that while loop.

I think you need to add the following after line 35 since you were trying to access memory that wasn't allocated to you yet:
resultBuf.reserve(buf.size() + argBuf.size() );

Second, I think that the problem lies in the fact that the object that you create in line 46 is destroyed at the end of the function. That means that str3 gets nothing.
Last edited on
Topic archived. No new replies allowed.