473,714 Members | 2,418 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What's wrong with the member function?

fl
Hi,
I am learning C++ with C++ primer written by Lippman. The first output
line: cout << s1 << endl; works right. The second is wrong. I find the
problem is that s1 is destroyed in the call from "result += s;". And
even though the "result" is correct in the routine:

String
String::operato r+( const String &s ) const
{
String result = *this;
result += s;
return result;
}

It is wrong after callback. I am not sure where is the problem.
Because it is from the book example, maybe there is some little part I
do not notice. Thank you very much.

------------
#include <string.h>
#include <assert.h>

class String {
friend ostream&
operator<<( ostream&, String& );
public:
String( const char*);
String( int );
String operator+(const String &) const;
String& operator+=(cons t String &);
~String();
private:
int len;
char *str;
};

String::String( const char *s)
{
len = strlen( s );
str = new char[ len + 1 ];
assert( str != 0);
strcpy(str, s );
}

String::~String ()
{ delete str;
}

ostream& operator<<( ostream& os, String& str )
{
char *s = str.str;
while ( *s ) os.put( *s++ );
return os;
}

String&
String::operato r+=( const String &s )
{
len += s.len;
char *p = new char[len+1];
assert( p != 0);
strcpy(p,str);
strcat(p,s.str) ;
delete str;
str=p;
return *this;
}

String
String::operato r+( const String &s ) const
{
String result = *this;
result += s;
return result;
}
-----------------------
#include <iostream.h>
#include "String.h"

main()
{
String s1("gobbledy") ;
String s2("gook");
s1 += s2;
cout << s1 << endl;

String s3 = s1 + s2;
cout << s3 << endl;

return 0;
}

Dec 28 '07 #1
7 1364
On 2007-12-28 11:56:02 -0500, fl <rx*****@gmail. comsaid:
Hi,
I am learning C++ with C++ primer written by Lippman. The first output
line: cout << s1 << endl; works right. The second is wrong. I find the
problem is that s1 is destroyed in the call from "result += s;". And
even though the "result" is correct in the routine:

String
String::operato r+( const String &s ) const
{
String result = *this;
result += s;
return result;
}

It is wrong after callback. I am not sure where is the problem.
Because it is from the book example, maybe there is some little part I
do not notice. Thank you very much.

------------
#include <string.h>
#include <assert.h>

class String {
friend ostream&
operator<<( ostream&, String& );
public:
String( const char*);
String( int );
String operator+(const String &) const;
String& operator+=(cons t String &);
~String();
private:
int len;
char *str;
};

String::String( const char *s)
{
len = strlen( s );
str = new char[ len + 1 ];
assert( str != 0);
strcpy(str, s );
}

String::~String ()
{ delete str;
}

ostream& operator<<( ostream& os, String& str )
{
char *s = str.str;
while ( *s ) os.put( *s++ );
return os;
}

String&
String::operato r+=( const String &s )
{
len += s.len;
char *p = new char[len+1];
assert( p != 0);
strcpy(p,str);
strcat(p,s.str) ;
delete str;
str=p;
return *this;
}

String
String::operato r+( const String &s ) const
{
String result = *this;
result += s;
return result;
}
-----------------------
#include <iostream.h>
#include "String.h"

main()
{
String s1("gobbledy") ;
String s2("gook");
s1 += s2;
cout << s1 << endl;

String s3 = s1 + s2;
What do you think the [default] copy constructor is doing in the line above?
cout << s3 << endl;

return 0;
}
--

-kira

Dec 28 '07 #2
fl
On 28 déc, 12:29, Kira Yamato <kira...@earthl ink.netwrote:
On 2007-12-28 11:56:02 -0500, fl <rxjw...@gmail. comsaid:


Hi,
I am learning C++ with C++ primer written by Lippman. The first output
line: cout << s1 << endl; works right. The second is wrong. I find the
problem is that s1 is destroyed in the call from "result += s;". *And
even though the "result" is correct in the routine:
String
String::operato r+( const String &s ) const
{
* *String result = *this;
* *result += s;
* *return result;
}
It is wrong after callback. I am not sure where is the problem.
Because it is from the book example, maybe there is some little part I
do not notice. Thank you very much.
------------
#include <string.h>
#include <assert.h>
class String {
* *friend ostream&
* * * * * *operator<<( ostream&, String& );
public:
* *String( const char*);
* *String( int );
* *String operator+(const String &) const;
* *String& operator+=(cons t String &);
* *~String();
private:
* *int len;
* *char *str;
};
String::String( const char *s)
{
* *len = strlen( s );
* *str = new char[ len + 1 ];
* *assert( str != 0);
* *strcpy(str, s );
}
String::~String ()
{ *delete str;
}
ostream& operator<<( ostream& os, String& str )
{
* *char *s = str.str;
* *while ( *s ) os.put( *s++ );
* *return os;
}
String&
String::operato r+=( const String &s )
{
* *len += s.len;
* *char *p = new char[len+1];
* *assert( p != 0);
* *strcpy(p,str);
* *strcat(p,s.str );
* *delete str;
* *str=p;
* *return *this;
}
String
String::operato r+( const String &s ) const
{
* *String result = *this;
* *result += s;
* *return result;
}
-----------------------
#include <iostream.h>
#include "String.h"
main()
{
* *String s1("gobbledy") ;
* *String s2("gook");
* *s1 += s2;
* *cout << s1 << endl;
* *String s3 = s1 + s2;

What do you think the [default] copy constructor is doing in the line above?
* *cout << s3 << endl;
* *return 0;
}

--

-kira- Masquer le texte des messages précédents -

- Afficher le texte des messages précédents -
You mean this:
s1 += s2;
cout << s1 << endl;

It corrects. But the book later propose the s3=s1+s2 as a new
concatenation method. From the context, it implies they can work
together (It says it uses the += operator of the previous definition).
Thanks.
Dec 28 '07 #3
fl wrote:
>What do you think the [default] copy constructor is doing in the line
above?
cout << s3 << endl;
return 0;
}

--

-kira- Masquer le texte des messages précédents -

- Afficher le texte des messages précédents -

You mean this:
s1 += s2;
cout << s1 << endl;

It corrects. But the book later propose the s3=s1+s2 as a new
concatenation method.
But you did not write that. You wrote:

String s3 = s1 + s2;
From the context, it implies they can work together (It says it uses the
+= operator of the previous definition).
Thanks.
Yes, but the line you wrote in your program uses the copy constructor. Since
you didn't define one, the compiler generates one for you, but in this
case, it doesn't do what you want.
The "Rule of Three" applies: If you need to write one of copy constructor,
copy assignment operator and destructor, you can be pretty certain that you
need all three of them.

Dec 28 '07 #4
fl
On 28 déc, 13:45, Rolf Magnus <ramag...@t-online.dewrote:
fl wrote:
What do you think the [default] copy constructor is doing in the line
above?
cout << s3 << endl;
return 0;
}
--
-kira- Masquer le texte des messages précédents -
- Afficher le texte des messages précédents -
You mean this:
* s1 += s2;
* cout << s1 << endl;
It corrects. But the book later propose the s3=s1+s2 as a new
concatenation method.

But you did not write that. You wrote:

String s3 = s1 + s2;
From the context, it implies they can work together (It says it uses the
+= operator of the previous definition).
Thanks.

Yes, but the line you wrote in your program uses the copy
constructor.
Thanks. Because it is new to me, I would like to be clear with what
you mean. The follow is my new copy constructor? I see the follow is
called.

String
String::operato r+( const String &s ) const
{
String result = *this;
result += s;
return result;

}

And I have to write the respective assignment operator and destructor?

Since
you didn't define one, the compiler generates one for you, but in this
case, it doesn't do what you want.
The "Rule of Three" applies: If you need to write one of copy constructor,
copy assignment operator and destructor, you can be pretty certain that you
need all three of them.- Masquer le texte des messages précédents -

- Afficher le texte des messages précédents -
Dec 28 '07 #5
fl
On 28 déc, 13:45, Rolf Magnus <ramag...@t-online.dewrote:
fl wrote:
What do you think the [default] copy constructor is doing in the line
above?
cout << s3 << endl;
return 0;
}
--
-kira- Masquer le texte des messages précédents -
- Afficher le texte des messages précédents -
You mean this:
* s1 += s2;
* cout << s1 << endl;
It corrects. But the book later propose the s3=s1+s2 as a new
concatenation method.

But you did not write that. You wrote:

String s3 = s1 + s2;
From the context, it implies they can work together (It says it uses the
+= operator of the previous definition).
Thanks.

Yes, but the line you wrote in your program uses the copy constructor. Since
you didn't define one, the compiler generates one for you, but in this
case, it doesn't do what you want.
The "Rule of Three" applies: If you need to write one of copy constructor,
copy assignment operator and destructor, you can be pretty certain that you
need all three of them.- Masquer le texte des messages précédents -

- Afficher le texte des messages précédents -
Thanks to both of you. I solve it now.
Dec 28 '07 #6
On Fri, 28 Dec 2007 08:56:02 -0800, fl wrote:
Hi,
I am learning C++ with C++ primer written by Lippman. The first output
line: cout << s1 << endl; works right. The second is wrong. I find the
problem is that s1 is destroyed in the call from "result += s;". And
even though the "result" is correct in the routine:

String
String::operato r+( const String &s ) const {
String result = *this;
result += s;
return result;
}

It is wrong after callback. I am not sure where is the problem. Because
it is from the book example, maybe there is some little part I do not
notice. Thank you very much.

------------
#include <string.h>
#include <assert.h>

class String {
friend ostream&
operator<<( ostream&, String& );
Are you sure the operator is going to change the String argument?
public:
String( const char*);
String( int );
String operator+(const String &) const; String& operator+=(cons t
String
&);
~String();
private:
int len;
char *str;
};
You forgot about copy constructor (as Kira Yamato noticed)
public:
String( const String & rhs);
>
String::String( const char *s)
{
len = strlen( s );
str = new char[ len + 1 ];
assert( str != 0);
This will never happen. If new fails, bad_alloc is thrown.
strcpy(str, s );
}

String::~String ()
{ delete str;
}
Undefined behaviour. It should be
delete[] str;
>
ostream& operator<<( ostream& os, String& str ) {
char *s = str.str;
while ( *s ) os.put( *s++ );
return os;
}
You don't change the str argument, so pass a const reference.
And code

os << str.str;
return os;

seems better to me
>
String&
String::operato r+=( const String &s ) {
len += s.len;
char *p = new char[len+1];
assert( p != 0);
strcpy(p,str);
strcat(p,s.str) ;
delete str;
str=p;
return *this;
}

String
String::operato r+( const String &s ) const {
String result = *this;
result += s;
return result;
}
-----------------------
#include <iostream.h>
#include "String.h"

main()
{
String s1("gobbledy") ;
String s2("gook");
s1 += s2;
cout << s1 << endl;

String s3 = s1 + s2;
cout << s3 << endl;

return 0;
}

--
Tadeusz B. Kopec (tk****@NOSPAMP LEASElife.pl)
A day for firm decisions!!!!! Or is it?
Dec 28 '07 #7
fl
On 28 déc, 15:53, "Tadeusz B. Kopec" <tko...@NOSPAMP LEASElife.pl>
wrote:
On Fri, 28 Dec 2007 08:56:02 -0800, fl wrote:
Hi,
I am learning C++ with C++ primer written by Lippman. The first output
line: cout << s1 << endl; works right. The second is wrong. I find the
problem is that s1 is destroyed in the call from "result += s;". *And
even though the "result" is correct in the routine:
String
String::operato r+( const String &s ) const {
* *String result = *this;
* *result += s;
* *return result;
}
It is wrong after callback. I am not sure where is the problem. Because
it is from the book example, maybe there is some little part I do not
notice. Thank you very much.
------------
#include <string.h>
#include <assert.h>
class String {
* *friend ostream&
* * * * * *operator<<( ostream&, String& );

Are you sure the operator is going to change the String argument?
public:
* *String( const char*);
* *String( int );
* *String operator+(const String &) const; String& operator+=(cons t
String
* *&);
* *~String();
private:
* *int len;
* *char *str;
};

You forgot about copy constructor (as Kira Yamato noticed)
public:
* String( const String & rhs);
String::String( const char *s)
{
* *len = strlen( s );
* *str = new char[ len + 1 ];
* *assert( str != 0);

This will never happen. If new fails, bad_alloc is thrown.
* *strcpy(str, s );
}
String::~String ()
{ *delete str;
}

Undefined behaviour. It should be
delete[] str;
ostream& operator<<( ostream& os, String& str ) {
* *char *s = str.str;
* *while ( *s ) os.put( *s++ );
* *return os;
}

You don't change the str argument, so pass a const reference.
And code

* * os << str.str;
* * return os;

seems better to me


String&
String::operato r+=( const String &s ) {
* *len += s.len;
* *char *p = new char[len+1];
* *assert( p != 0);
* *strcpy(p,str);
* *strcat(p,s.str );
* *delete str;
* *str=p;
* *return *this;
}
String
String::operato r+( const String &s ) const {
* *String result = *this;
* *result += s;
* *return result;
}
-----------------------
#include <iostream.h>
#include "String.h"
main()
{
* *String s1("gobbledy") ;
* *String s2("gook");
* *s1 += s2;
* *cout << s1 << endl;
* *String s3 = s1 + s2;
* *cout << s3 << endl;
* *return 0;
}

--
Tadeusz B. Kopec (tko...@NOSPAMP LEASElife.pl)
A day for firm decisions!!!!! *Or is it?- Masquer le texte des messages précédents -

- Afficher le texte des messages précédents -- Masquer le texte des messages précédents -

- Afficher le texte des messages précédents -
Thank you very much. I am really new to CPP, quite different from C.
Seems too much implicit in CPP, interesting. Happy holidays.
Dec 28 '07 #8

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

Similar topics

3
2523
by: Philippe Guglielmetti | last post by:
Look at these few lines of code: class A { public: virtual void f() { cout << "A";}}; class B : public A{public: static void f() { cout << "B"; }}; class C : public B{public: void f() { cout << "C"; }}; // virtual or not ? that's the question... int main(int, char**) { A* x; A a; B b; C c;
3
2373
by: Roman Simkin | last post by:
Hi, As far as I know, a static variable is a variable that belongs to a function or a class (are there any other options?). I've seen somewhere a function that *returns* static types - something like: static someType myFunction() {...} What is the meaning of it?? Or did I get something wrong?
20
2561
by: Sam | last post by:
Hi I'm learning to code with C++ and wrote some very simple code. I think it's consistent with every rule but always got compiling errors that I don't understand. The code include 5 files as following, delimited by //////: ////////////////pose.h #ifndef pose_h #define pose_h #include "point.h"
12
3301
by: Steven T. Hatton | last post by:
This is something I've been looking at because it is central to a currently broken part of the KDevelop new application wizard. I'm not complaining about it being broken, It's a CVS images. Such things happen. The whole subsystem is going through radical changes. I don't really want to say what I think of the code just yet. That would influence the opinions of others, and I really want to know how other people view these things,...
9
1905
by: jlopes | last post by:
There seems to bet no diff between a vitual method and an inheirited method. class A_Base { public: virtual void filter(){ /* some code */ } }; class D_of_A_Base : public A_Base {
8
1932
by: Crash | last post by:
2 Questions, but first Consider this: I'm looking at a C++ class (patterned using the Singleton Design Pattern). It has some public and private operations. It runs quite happily seving the time and date to everybody. The private operations setTheTime() and setTheDate() I require to be called/influenced externally. For instance a class SubsysA has the right to call setTheTime() only, and class SubsysB has the right to setTheDate() only. ...
39
3185
by: utab | last post by:
Dear all, Is there a clear distinction how to decide which functions to be members of a class and which not How is your attitude (Your general way from your experiences ...) "If the function changes the state of the object, it ought to be a member of that object." Reference Accelerated C++, A. Koenig, page 159.
5
1474
by: sunny | last post by:
hai i am not able to overload a member function of base class in derived calss.what is the wrong thning i am doing here in the following program. # include<iostream> using namespace std; class Quad
4
6691
by: grizggg | last post by:
I have searched and not found an answer to this question. I ran upon the following statement in a *.cpp file in a member function: static const char * const pacz_HTMLContentTypeHeader = "Content-Type: text/html\r\n"; Why is the second const needed and what does it do? Thanks
16
3436
by: John Doe | last post by:
Hi, I wrote a small class to enumerate available networks on a smartphone : class CNetwork { public: CNetwork() {}; CNetwork(CString& netName, GUID netguid): _netname(netName), _netguid(netguid) {}
0
8707
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9314
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9174
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9074
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7953
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6634
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4464
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2520
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2110
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.