473,474 Members | 1,324 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

overloading +=

hey guys, my assignment is to write a string class. below is all of my code.
When i try to overload the += operator, my program crashes every single
time. could some one check my code, and see what I am doing wrong please?
Thank You.

P.s. i would appreciate a promt response, i was due today, but if i finish
it soon my teacher might accept it. also if you have any ideas on how to
compare two c-strings using lexiographic ordeing please let me know.

#include <iostream>
#include "MyString.h"
#include <fstream>
#include <cassert>
#include <string>
using namespace std; //introduces namespace std

int main ( void )
{
MyString a("rr");
MyString b("aaa");
a+=b;
cout<<a;
return 0;
}
MyString::MyString()
{

string = "";
}

MyString::MyString(const char *inString)
{
string = new char[strlen(inString)+1];
strcpy(string,inString);
}
MyString::~MyString()
{
delete []string;
}

ostream& operator<<(ostream &out,const MyString &outString)
{
out<<outString.string;
return out;
}
MyString MyString:: operator=(MyString &right)
{
if (this != &right)
{
delete []string;
string = new char[strlen(right.string)+1];
strcpy(string,right.string);
}
return *this;
}
MyString::MyString(MyString &right)
{
string = new char[strlen(right.string)+1];
strcpy(string,right.string);
}
char& MyString::operator[](int index)
{
assert(index>=0 && index < strlen(string));
return string[index];
}
char MyString::operator[](int index)const
{
assert(index>=0 && index < strlen(string));
return string[index];
}
char *operator+(const MyString left,const MyString right)
{
char *temp;
temp = new char[strlen(left.string)+strlen(right.string)+1];
temp = strcat(left.string,right.string);
return temp;

}

istream& operator>>(istream& in,MyString &inString)
{

char temp[128];
delete [] inString.string;
in>>temp;
strcpy(inString.string,temp);

return in;
}
void MyString::read(istream &inString,char delimit)
{
char temp[128];
delete []string;
inString.getline(temp,127,delimit);
strcpy(string,temp);
}

char MyString:: operator+=(const MyString right)
{
MyString temp;
temp = *this;
delete []temp.string;
temp.string = new char[strlen(temp.string)+strlen(right.string)+1];
strcat(temp.string,right.string);
strcpy(string,temp.string);
return temp.string;
}
/* these are not working yet
bool operator<(const MyString left,const MyString right)
{

if(strcmp(left.string,right.string)<0)
return true;
}
bool operator>(const MyString left,const MyString right)
{

if(strcmp(left.string,right.string)>0)
return true;
}
*/
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
using namespace std;

class MyString {
public:
//Constructors, Copy, and Destrctors

MyString(); //one of four
MyString(const char *inString); //two of four
MyString operator=(MyString &right); //three of four
MyString(MyString &right); //four of four
~MyString(); //destructor

//input/output
friend ostream& operator<<(ostream& out,const MyString &outString);
friend istream& operator>>(istream& in,MyString &inString);
void read(istream& inString,char delimit);
//Overloaded brackets
char& operator[](int index);
char operator[](int index)const;
//overloaded '+' & +=
char* operator+=(const MyString right);
friend char* operator+(const MyString left,const MyString right);
//Comparison operators
/*
friend bool operator<(const MyString left,const MyString right);
friend bool operator>(const MyString left,const MyString right);
*/
private:
operator>(const MyString left,const MyString right);
*/
};

#endif


Jul 19 '05 #1
3 1986
> int main ( void )
{
MyString a("rr");
MyString b("aaa");
a+=b;
cout<<a;
See forward notes, and you can see you are doing an access to
uninitilized memory, causing a segmentation fault.
return 0;
}
MyString::MyString()
{
string = "";
}
If you do this initializing of string, you cannot do delete[] string in
any other point of your code. You cannot delete an static "".
MyString::MyString(const char *inString)
{
string = new char[strlen(inString)+1];
strcpy(string,inString);
}
MyString::~MyString()
{
delete []string;
If you do Mystring* a=new MyString(); delete a; your program will crash
also.
}

ostream& operator<<(ostream &out,const MyString &outString)
{
out<<outString.string;
return out;
}

char& MyString::operator[](int index)
{
assert(index>=0 && index < strlen(string));
return string[index];
}
char MyString::operator[](int index)const
{
assert(index>=0 && index < strlen(string));
return string[index];
}
char *operator+(const MyString left,const MyString right)
{
char *temp;
temp = new char[strlen(left.string)+strlen(right.string)+1];
temp = strcat(left.string,right.string);
return temp;

}
don't Operator+ must return a MyString& ???
istream& operator>>(istream& in,MyString &inString)
{

char temp[128];
delete [] inString.string;
in>>temp;
Where are you allocating inString.string buffer? you delete it, but dont
realloc the new buffer.
strcpy(inString.string,temp);

return in;
}
void MyString::read(istream &inString,char delimit)
{
char temp[128];
delete []string;
inString.getline(temp,127,delimit);
Again string isnt a valid pointer. You dont allocate new buffer for string.
strcpy(string,temp);
}

char MyString:: operator+=(const MyString right)
{
MyString temp;
temp = *this;
delete []temp.string;
temp.string = new char[strlen(temp.string)+strlen(right.string)+1];
strcat(temp.string,right.string);
temp.string is reallocated, but string may have enough space or not. You
cannot strcpy from temp.string to string, because string is not a know
size buffer.
strcpy(string,temp.string);
return temp.string;
}
/* these are not working yet
bool operator<(const MyString left,const MyString right)
{

if(strcmp(left.string,right.string)<0)
return true;
}
bool operator>(const MyString left,const MyString right)
{

if(strcmp(left.string,right.string)>0)
return true;
}
*/
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
using namespace std;

class MyString {
public:
//Constructors, Copy, and Destrctors

MyString(); //one of four
MyString(const char *inString); //two of four
MyString operator=(MyString &right); //three of four
MyString(MyString &right); //four of four
~MyString(); //destructor

//input/output
friend ostream& operator<<(ostream& out,const MyString &outString);
friend istream& operator>>(istream& in,MyString &inString);
void read(istream& inString,char delimit);
//Overloaded brackets
char& operator[](int index);
char operator[](int index)const;
//overloaded '+' & +=
char* operator+=(const MyString right);
friend char* operator+(const MyString left,const MyString right);
//Comparison operators
/*
friend bool operator<(const MyString left,const MyString right);
friend bool operator>(const MyString left,const MyString right);
*/
private:
operator>(const MyString left,const MyString right);
*/
};

#endif

--
-----------------------------------

Juan Antonio Domínguez Pérez
http://www.dominpe.com

Jul 19 '05 #2


Luis wrote:


char *operator+(const MyString left,const MyString right)
Why does that one return a character pointer?
operator+, +=, * and all the other arithmetic operators usually
return either a reference or an object of the same class type they
are defined for.
{
char *temp;
temp = new char[strlen(left.string)+strlen(right.string)+1];
temp = strcat(left.string,right.string);
return temp;

} [snip]
char MyString:: operator+=(const MyString right)
Are you sure that the result of adding a MyString object to another
MyString object equals a single character?
{
MyString temp;
temp = *this;
creating a copy of *this ...
delete []temp.string;
deleting the characters stored in the temporary ...
temp.string = new char[strlen(temp.string)+strlen(right.string)+1];
accessing the previously deleted characters in the temporary.
Kaboom.
strcat(temp.string,right.string);
adding the characters from the 'right' string to a non existing
string in temp.string. temp.string just points at some memory, nothing
is stored there right now.
Kaboom.
strcpy(string,temp.string);
return temp.string;

}


Also: usually arguments to operators are passed by const reference.
So a typical framework for your operators would look like this:

MyString operator+( const MyString& left, const MyString& right )
{
MyString result;
...
return result;
}

MyString& MyString::operator+=( const MyString& right )
{
...
return *this;
}

Note the difference: operator+ creates a temporary which will hold the result.
Thus you can't return by reference, you have to return by value.
operator+= on the other hand works on the object it is called for. This object
is still around after the function finishes, thus operator+= can return a reference.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 19 '05 #3
> hey guys, my assignment is to write a string class. below is all of my
code.
When i try to overload the += operator, my program crashes every single time. could some one check my code, and see what I am doing wrong please? Thank You.

P.s. i would appreciate a promt response,
I you want prompt responses post minimal, yet complete and compilable
code that demonstates the problem. The easier it is for people to
reproduce the problem you are having, the more likely you get prompt
responses. The code you posted is not compilable, and has alot of stuff
that is not relevant to the problem you are having.
i was due today, but if i finish
it soon my teacher might accept it. also if you have any ideas on how to compare two c-strings using lexiographic ordeing please let me know.

#include <iostream>
#include "MyString.h"
#include <fstream>
#include <cassert>
#include <string>
using namespace std; // introduces namespace std
Redundant comment, don't explain standard language constructs with
comments.
int main ( void )
{
MyString a("rr");
MyString b("aaa");
a+=b;
cout<<a;

return 0;
}

MyString::MyString()
{

string = "";
}
This is going to give problems when you do 'delete[] string;' since
delete[] may only be done on objects allocated with new[]. This is
probably also explains the problem you are having with operator+= as
that function uses a default constructed MyString.

A quick fix would be to rewrite the default constructor like this:

MyString::MyString()
{
string = new char[1];
string[0] = 0;
}
MyString::MyString(const char *inString)
{
string = new char[strlen(inString)+1];
strcpy(string,inString);
}
MyString::~MyString()
{
delete []string;
}

ostream& operator<<(ostream &out,const MyString &outString)
{
out<<outString.string;
return out;
}

MyString MyString:: operator=(MyString &right)
{
if (this != &right)
{
delete []string;
string = new char[strlen(right.string)+1];
strcpy(string,right.string);
}
return *this;
}
Usually assignment operators return a reference to themselves
(MyString&) instead of a copy.
MyString::MyString(MyString &right)
{
string = new char[strlen(right.string)+1];
strcpy(string,right.string);
}
Copy constructors usually take a const reference (const MyString &)
rather than a reference to the object to be copied, because the object
to be copied should not be modified.
char& MyString::operator[](int index)
{
assert(index>=0 && index < strlen(string));
return string[index];
}

char MyString::operator[](int index)const
{
assert(index>=0 && index < strlen(string));
return string[index];
}

char *operator+(const MyString left,const MyString right)
{
char *temp;
temp = new char[strlen(left.string)+strlen(right.string)+1];
temp = strcat(left.string,right.string);
return temp;
}
Don't return a char pointer, this creates a memory leak:

MyString a("Memory");
MyString b("Leak!!!");
MyString c(a+b); // Memory allocated by operator+ will not be
released!

operator+ should return a MyString object. It is also wise to use const
references (const MyString &) for the input parameters.
istream& operator>>(istream& in,MyString &inString)
{

char temp[128];
delete [] inString.string;
in>>temp;
strcpy(inString.string,temp);

return in;
}
This is going to fail miserably when more than 128 characters come from
the 'in' stream.
void MyString::read(istream &inString,char delimit)
{
char temp[128];
delete []string;
inString.getline(temp,127,delimit);
strcpy(string,temp);
}

char MyString:: operator+=(const MyString right)
It doesn't make sense to return just a char (it also mismatches with the
header file you posted);
return a reference to self (MyString&) instead
{
MyString temp;
temp = *this;
delete []temp.string;
See my comment I made for the default constructor; you are deleting
something here that has not been allocated with new[]!!!
temp.string = new char[strlen(temp.string)+strlen(right.string)+1]; strcat(temp.string,right.string);
strcpy(string,temp.string);
return temp.string;
}
Since you only using the string member of the temp object, you might
just as well use a local char* variable instead. Using a temporary
MyString object has absolutely no added value here, it only complicates
things.
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
using namespace std;


Never put a using statement in a header file like this. Everyone
including this header file pulls the std namespace into the current
namespace without knowing it. This can lead to very difficult to track
down problems.

<snip>

--
Peter van Merkerk
peter.van.merkerk(at)dse.nl
Jul 19 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: Terje Slettebø | last post by:
To round off my trilogy of "why"'s about PHP... :) If this subject have been discussed before, I'd appreciate a pointer to it. I again haven't found it in a search of the PHP groups. The PHP...
4
by: Dave Theese | last post by:
Hello all, I'm trying to get a grasp of the difference between specializing a function template and overloading it. The example below has a primary template, a specialization and an overload. ...
5
by: | last post by:
Hi all, I've been using C++ for quite a while now and I've come to the point where I need to overload new and delete inorder to track memory and probably some profiling stuff too. I know that...
39
by: zeus | last post by:
I know function overloading is not supported in C. I have a few questions about this: 1. Why? is it from technical reasons? if so, which? 2. why wasn't it introduced to the ANSI? 3. Is there any...
45
by: JaSeong Ju | last post by:
I would like to overload a C function. Is there any easy way to do this?
31
by: | last post by:
Hi, Why can I not overload on just the return type? Say for example. public int blah(int x) { }
2
by: brzozo2 | last post by:
Hello, this program might look abit long, but it's pretty simple and easy to follow. What it does is read from a file, outputs the contents to screen, and then writes them to a different file. It...
15
by: lordkain | last post by:
is it possible to do some kind of function overloading in c? and that the return type is different
11
by: placid | last post by:
Hi all, Is it possible to be able to do the following in Python? class Test: def __init__(self): pass def puts(self, str): print str
10
by: Matthew | last post by:
Am I correct in thinking there is no method/function overloading of any kind in any version of PHP? Thanks, Matthew
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.