473,320 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Why does not this main test program work

Hello!!

I have done some operator overloading but my main testprogram doesn't work
well.

Have you any idea which of my methods are wrong?

#include <iostream>
#include <string>
using namespace std;

class String
{
friend ostream& operator<<(ostream& os, const String& s);
public:
/*explicit*/ String(const char* s);
String(const String& s);
~String() { if(buffer) delete[] buffer; buffer = 0; }
String& operator=(const String& s);
int operator==(const String& s) const; // bool
int operator!=(const String& s) const; // bool
String operator+(const String& s);
String& operator+=(const String& s);

private:
char* buffer;
int size;
};

ostream& operator<<(ostream& os, const String& s)
{
os << s.buffer;
return os;
}

String::String(const char* s)
{
size = strlen(s);
buffer = new char[size+1];
strcpy(buffer, s);
}

String::String(const String& s)
{
size = s.size;
buffer = new char[size+1];
strcpy(buffer, s.buffer);
}

String& String::operator=(const String& s)
{
if (buffer)
delete [] buffer;
buffer = new char[strlen(s.buffer)+1];
strcpy(buffer, s.buffer);
return *this;
}

int String::operator==(const String& s) const
{
if (strcmp(buffer, s.buffer) == 0)
return 1;
else
return 0;
}
int String::operator!=(const String& s) const
{
if (strcmp(buffer, s.buffer))
return 1;
else
return 0;
}

String String::operator+(const String& s)
{
char* str = new char[strlen(buffer) + strlen(s.buffer) + 2];
String local(str);
strcpy(local.buffer, "");
strcat(local.buffer, buffer);
strcat(local.buffer, s.buffer);
return local;
}

String& String::operator+=(const String& s)
{
char* str = new char[strlen(buffer) + strlen(s.buffer) + 1];
String local(str);
strcpy(local.buffer, "");
strcat(local.buffer, buffer);
strcat(local.buffer, s.buffer);
delete [] buffer;
buffer = local.buffer;
size = local.size;
return *this;
}

int main()
{
String s1("Hej");
String s2(" du glade");
String s3(" ta en spade");
String s4(s1 + s2 + s3);
String s5("Test ");
String s6(" av program");
s5 += s6;
cout << s1 << endl << s2 << endl << s3 << endl
<< s4 << endl << s5 << endl << s6 << endl;

return 0;
}

Many thanks

//Tony
Dec 30 '05 #1
4 1730
Tony Johansson wrote:
Hello!!

I have done some operator overloading but my main testprogram doesn't work
well.

[snip]

In what way does it not work well? Does it compile? Does it run without
crashing? Does it give incorrect results? Etc.

Cheers! --M

Dec 30 '05 #2
Tony Johansson wrote:
Hello!!

I have done some operator overloading but my main testprogram doesn't work
well.
I assume this is only an exercise and you are aware of std::string.
Have you any idea which of my methods are wrong?

#include <iostream>
#include <string>
using namespace std;
http://www.parashift.com/c++-faq-lit....html#faq-27.5
class String
{
friend ostream& operator<<(ostream& os, const String& s);
public:
/*explicit*/ String(const char* s);
String(const String& s);
~String() { if(buffer) delete[] buffer; buffer = 0; }
delete handles null pointer automatically.
String& operator=(const String& s);
int operator==(const String& s) const; // bool
int operator!=(const String& s) const; // bool
well.. you *are* aware that there is a bool type in C++, aren't you?
String operator+(const String& s);
String& operator+=(const String& s);

private:
char* buffer;
int size;
};

ostream& operator<<(ostream& os, const String& s)
{
os << s.buffer;
return os;
}

String::String(const char* s)
Take the habit of initializing objects.

: size(0), buffer(0)
{
size = strlen(s);
buffer = new char[size+1];
strcpy(buffer, s);
}

String::String(const String& s)
{
size = s.size;
buffer = new char[size+1];
strcpy(buffer, s.buffer);
}

String& String::operator=(const String& s)
{
if (buffer)
delete [] buffer;
buffer = new char[strlen(s.buffer)+1];
why not use s.size?
strcpy(buffer, s.buffer);
return *this;
}

int String::operator==(const String& s) const
{
if (strcmp(buffer, s.buffer) == 0)
return 1;
else
return 0;
}
this should be

bool String::operator==(const String& s) const
{
if (strcmp(buffer, s.buffer) == 0)
return true;
else
return false;
}
int String::operator!=(const String& s) const
{
if (strcmp(buffer, s.buffer))
return 1;
else
return 0;
}
Idem.
String String::operator+(const String& s)
{
char* str = new char[strlen(buffer) + strlen(s.buffer) + 2];
String local(str);
Watch out! str contains garbage here. this won't work! You should
construct the string in str *before* creating local.
strcpy(local.buffer, "");
strcat(local.buffer, buffer);
strcat(local.buffer, s.buffer);
return local;
}

String& String::operator+=(const String& s)
{
char* str = new char[strlen(buffer) + strlen(s.buffer) + 1];
Same here.
String local(str);
strcpy(local.buffer, "");
strcat(local.buffer, buffer);
strcat(local.buffer, s.buffer);
delete [] buffer;
buffer = local.buffer;
size = local.size;
return *this;
}

int main()
{
String s1("Hej");
String s2(" du glade");
String s3(" ta en spade");
String s4(s1 + s2 + s3);
String s5("Test ");
String s6(" av program");
s5 += s6;
cout << s1 << endl << s2 << endl << s3 << endl
<< s4 << endl << s5 << endl << s6 << endl;

return 0;
}


I didn't test it, but if it still doesn't work, be more explicit than
"my main testprogram doesn't work well" and we'll be able to help you
more.
Jonathan

Dec 30 '05 #3
"Tony Johansson" <jo*****************@telia.com> schrieb im Newsbeitrag
news:sO*********************@newsc.telia.net...
Hello!!

I have done some operator overloading but my main testprogram doesn't work
well.
It doesn't work well? It doesn't work.

Have you any idea which of my methods are wrong?

#include <iostream>
#include <string>
using namespace std;

class String
{
friend ostream& operator<<(ostream& os, const String& s);
public:
/*explicit*/ String(const char* s);
String(const String& s);
~String() { if(buffer) delete[] buffer; buffer = 0; }
String& operator=(const String& s);
int operator==(const String& s) const; // bool
int operator!=(const String& s) const; // bool
Why do these operators return an int? Why not a bool?
String operator+(const String& s);
String& operator+=(const String& s);

private:
char* buffer;
int size;
};

ostream& operator<<(ostream& os, const String& s)
{
os << s.buffer;
return os;
}

String::String(const char* s)
{
size = strlen(s);
buffer = new char[size+1];
strcpy(buffer, s);
}

String::String(const String& s)
{
size = s.size;
buffer = new char[size+1];
strcpy(buffer, s.buffer);
}

String& String::operator=(const String& s)
{
if (buffer)
delete [] buffer;
buffer = new char[strlen(s.buffer)+1];
strcpy(buffer, s.buffer);
return *this;
}
What will happen if you try to assign a string variable to itself? Like

String s("Some String");
s = s;

That might look stupid, but it could happen when a function receives to
string parameters and the caller passes the same variable twice. Also, you
do not keep track of the size of the string. If you don't need its size,
don't add a member to hold it. And if you add such a member, take care that
it holds the proper value. Try something like

char* str = new char[s.size + 1];
strcpy(str, s.buffer);
delete[] buffer;
buffer = str;
size = s.size;
return *this;
int String::operator==(const String& s) const
{
if (strcmp(buffer, s.buffer) == 0)
return 1;
else
return 0;
}
This function's body could also be written as

return strcmp(buffer, s.buffer) == 0;
int String::operator!=(const String& s) const
{
if (strcmp(buffer, s.buffer))
strcmp does not return a boolean value. So don't omit the comparison. After
all, in the function above, you didn't wite !strcmp(...) either.
return 1;
else
return 0;
}

String String::operator+(const String& s)
{
char* str = new char[strlen(buffer) + strlen(s.buffer) + 2];
Why do you want to append two extra characters?
String local(str);
Now you try to initialize a local String variable with something that has
not been initialized. You cannot expect the new'ed memory to contain a
0-terminated string. And what are you trying to do? String's constructor
makes its private copy of the specified string, a string to which no value
has been assigned. You have allocated memory for some string, but you never
initialized that memory.
strcpy(local.buffer, "");
strcat(local.buffer, buffer);
strcat(local.buffer, s.buffer);
return local;
}
You should rearrange you code a little bit:

char* str = new char[strlen(buffer) + strlen(s.buffer) + 1];
strcpy(str, buffer);
strcat(str, s.buffer);
String local(str);
delete[] str;
return local;

But it would be much better to use operator+= to implement operator+:

String local(*this);
local += s;
return local;
String& String::operator+=(const String& s)
{
char* str = new char[strlen(buffer) + strlen(s.buffer) + 1];
String local(str);
strcpy(local.buffer, "");
strcat(local.buffer, buffer);
strcat(local.buffer, s.buffer);
delete [] buffer;
buffer = local.buffer;
size = local.size;
return *this;
}
Here you have similiar problems as in your implementation of operator+. Try

char* str = new char[size + s.size + 1];
strcpy(str, buffer);
strcpy(str + size, s.buffer);
delete[] buffer;
buffer = str;
size += s.size;
return *this;
int main()
{
String s1("Hej");
String s2(" du glade");
String s3(" ta en spade");
String s4(s1 + s2 + s3);
String s5("Test ");
String s6(" av program");
s5 += s6;
cout << s1 << endl << s2 << endl << s3 << endl
<< s4 << endl << s5 << endl << s6 << endl;

return 0;
}

Many thanks

//Tony


HTH
Heinz
Dec 30 '05 #4
On Fri, 30 Dec 2005 21:39:36 GMT in comp.lang.c++, "Tony Johansson"
<jo*****************@telia.com> wrote,
String String::operator+(const String& s)
{
char* str = new char[strlen(buffer) + strlen(s.buffer) + 2];
String local(str);


Why do you think it doesn't work? How do the results differ from
your expectations?

Among several mistakes, the above appears to be the most immediate
problem. You allocate some chars with new, which are uninitialized,
then you construct a String that is looking for the end of those
uninitialized chars. Goofyness follows.

Several of your methods fail to set this->size where required.

A proper nonmember operator+() is more like:

String operator+(const String& left, const String& right)
{
String result(left);
result += right;
return result;
}

Of course that depends on a proper operator+=(), copy constructor,
etc.

Dec 30 '05 #5

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

Similar topics

12
by: Fred Pacquier | last post by:
First off, sorry for this message-in-a-bottle-like post... I haven't been able to phrase my questions well enough to get a meaningful answer from Google in my research. OTOH, it is standard...
11
by: becte | last post by:
What does the standard say about f(x++) ? 1. x is incremented and then the that value is used in function f, i.e. x++; f(x); 2. the value of x (before ++) is send to f and after returning. x is...
75
by: Beni | last post by:
I have been programming in C for about a year now. It sounds silly, but I never took the time to question why a C(or C++ or Java) program execution begins only at the main(). Is it a convention or...
5
by: Bob Altman | last post by:
Hi all, I have a WinForms app that has no main window (just a module with a Sub Main). My Main routine calls a subroutine that wants to politely abort the application rather than return to its...
89
by: Cuthbert | last post by:
After compiling the source code with gcc v.4.1.1, I got a warning message: "/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the 'gets' function is dangerous and should not be...
20
by: JohnQ | last post by:
The way I understand the startup of a C++ program is: A.) The stuff that happens before the entry point. B.) The stuff that happens between the entry point and the calling of main(). C.)...
2
by: tonyjeffs2 | last post by:
//int _tmain(int argc, _TCHAR* argv) // main for windows int main(int argc, char *argv) // ... or main { cout <<argv<<endl; return 0; } //run at command line:...
17
by: mike-yue | last post by:
and, Is it possible to call one main function from another main function? Thanks guys.
13
blazedaces
by: blazedaces | last post by:
Hey guys, how's it going today? So basically I have a program that uses hotbits (a real online random number generator based off radioactive decay) to produce truly random alphanumeric codes (Note:...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.