473,804 Members | 2,070 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question--A function returns class object(comparin g C++ & JAVA)

Dear Sir,

I am a little puzzled about a function returning a class object, for
example, suppose I hava a class Money and a method:

Money lastYear(Money aMoney)
{
Money tempMoney;
...
return tempMoney;
}

Because in C++ the RETURNED is actually a new copy of the object(kind of
like passing by value), here a copy of tempMoney is returned, so
tempMoney will be useless, so after the statement of return, the object
tempMoney will be destroyed. Is this correct?

Now, if in JAVA(sorry, not offending), since always passing by
reference, if above code is Java, the RETURNED is the MEMORY ADDRESS of
the object tempMoney. So after the exit of the function, the object
tempMoney is referenced by other variable. So it stays existing. Is this
correct?

Thank you very much.

Dec 13 '05 #1
11 1813
Xiaoshen Li wrote:
I am a little puzzled about a function returning a class object, for
example, suppose I hava a class Money and a method:

Money lastYear(Money aMoney)
{
Money tempMoney;
...
return tempMoney;
}

Because in C++ the RETURNED is actually a new copy of the object(kind of
like passing by value), here a copy of tempMoney is returned, so
tempMoney will be useless, so after the statement of return, the object
tempMoney will be destroyed. Is this correct?
'tempMoney' is a local object. It will be destroyed when 'lastYear'
function finishes execution no matter what (or how) you return.
Now, if in JAVA(sorry, not offending), since always passing by
reference, if above code is Java, the RETURNED is the MEMORY ADDRESS of
the object tempMoney.
I'll take your word for it.
So after the exit of the function, the object
tempMoney is referenced by other variable. So it stays existing. Is this
correct?


Why don't you ask about Java internals in a Java newsgroup?

V
Dec 13 '05 #2
Victor Bazarov wrote:
Xiaoshen Li wrote:
I am a little puzzled about a function returning a class object, for
example, suppose I hava a class Money and a method:

Money lastYear(Money aMoney)
{
Money tempMoney;
...
return tempMoney;
}

Because in C++ the RETURNED is actually a new copy of the object(kind of
like passing by value), here a copy of tempMoney is returned, so
tempMoney will be useless, so after the statement of return, the object
tempMoney will be destroyed. Is this correct?


'tempMoney' is a local object. It will be destroyed when 'lastYear'
function finishes execution no matter what (or how) you return.


To the OP, you're correct that tempMoney is destroyed, but if by
"useless" you mean "unreferenc ed" then I suspect you may have
misunderstood the reason.

As Victor pointed out, tempMoney is destroyed as soon as it
passes out of scope simply because it is a local object. It has
nothing to do with whether any references to the object still
exist. For example, if you were unwise, you could have written:

// oops! returns a dangling reference
Money& lastYear(Money aMoney)
{
Money tempMoney;
....
return tempMoney;
}

In this case, tempMoney is still destroyed and the reference
returned by the function is bound to a non-existent object.
Unlike in Java, the existence of a reference has no impact on
the lifetime of the referenced object. Likewise, a pointer does
not affect the lifetime of the pointee. It's up to you to make
sure there are no dangling references or pointers.

Dec 13 '05 #3
ni*****@microso ft.com wrote:
[...]
Unlike in Java, the existence of a reference has no impact on
the lifetime of the referenced object.
Actually this is not generally true. If a temporary object has a const
reference bound to it, the temporary persists as long as the reference.
But the lifetime of a temporary is maintained at compile-time, not at
run-time. It's a special case, of course. And you're absolutely right
WRT pointers.
[..]


V
Dec 13 '05 #4
Thank you so much for helping me. I just got another question.

In C++, suppose with class Money:
Money aMoney, bMoney;
....
bMoney = aMoney;

Now bMoney refers to an identical object with aMoney refers to. But they
are two separate objects(but identical).

Is there a way to make bMoney refers to the SAME object as aMoney refers
to? (This question may be too simple to ask. Sorry, my mind is clogging.)

Dec 13 '05 #5
Xiaoshen Li schrieb:
Thank you so much for helping me. I just got another question.

In C++, suppose with class Money:
Money aMoney, bMoney;
...
bMoney = aMoney;

Now bMoney refers to an identical object with aMoney refers to. But they
are two separate objects(but identical).

Is there a way to make bMoney refers to the SAME object as aMoney refers
to? (This question may be too simple to ask. Sorry, my mind is clogging.)


Money aMoney;
Money &bMoney = aMoney;
Thomas
Dec 13 '05 #6
Xiaoshen Li wrote:
Thank you so much for helping me. I just got another question.

In C++, suppose with class Money:
Money aMoney, bMoney;
...
bMoney = aMoney;

Now bMoney refers to an identical object with aMoney refers to. But they
are two separate objects(but identical).
Since C++ has 'reference' type, and also 'iterator' and 'pointer' that can
actually _refer_ (or point) to something, let's avoid using that term here
because it can lead to confusion. 'bMoney' does not refer, it designates.
So, we should say 'bMoney' designates a separate object. Now, whether
they are truly identical is up for debate because we don't know how class
'Money' is implemented and what its 'operator=' actually does.
Is there a way to make bMoney refers to the SAME object as aMoney refers
to? (This question may be too simple to ask. Sorry, my mind is clogging.)


Money aMoney;
Money &bMoney = aMoney; // bMoney is a reference

There is no other way.

V
Dec 13 '05 #7


ni*****@microso ft.com wrote:

As Victor pointed out, tempMoney is destroyed as soon as it
passes out of scope simply because it is a local object. It has
nothing to do with whether any references to the object still
exist. For example, if you were unwise, you could have written:

// oops! returns a dangling reference
Money& lastYear(Money aMoney)
{
Money tempMoney;
....
return tempMoney;
}

In this case, tempMoney is still destroyed and the reference
returned by the function is bound to a non-existent object.
Unlike in Java, the existence of a reference has no impact on
the lifetime of the referenced object. Likewise, a pointer does
not affect the lifetime of the pointee. It's up to you to make
sure there are no dangling references or pointers.


I became so interested in seeing this so I wrote code to test it. BUT,
the results is not what you said. (I truely believe you are correct!).
With following function:

Money& lastYear(Money aMoney)
{
Money tempMoney;
tempMoney = aMoney;
return tempMoney;
}

Money bMoney = lastYear(aMoney );
bMoney.output() ;

I got warning when compiling. But running actually went through and
output() printed out the "correct" value, the same value as aMoney.
Based on what you said above, I would expect bMoney.output() prints out
garbage, since bMoney binds to a non-existent object. Could you give me
more help?

Thank you very much.

Dec 13 '05 #8
On Tue, 13 Dec 2005 19:35:50 +0000, Xiaoshen Li <xl**@gmu.edu > wrote:


ni*****@micros oft.com wrote:

As Victor pointed out, tempMoney is destroyed as soon as it
passes out of scope simply because it is a local object. It has
nothing to do with whether any references to the object still
exist. For example, if you were unwise, you could have written:

// oops! returns a dangling reference
Money& lastYear(Money aMoney)
{
Money tempMoney;
....
return tempMoney;
}

In this case, tempMoney is still destroyed and the reference
returned by the function is bound to a non-existent object.
Unlike in Java, the existence of a reference has no impact on
the lifetime of the referenced object. Likewise, a pointer does
not affect the lifetime of the pointee. It's up to you to make
sure there are no dangling references or pointers.


I became so interested in seeing this so I wrote code to test it. BUT,
the results is not what you said. (I truely believe you are correct!).
With following function:

Money& lastYear(Money aMoney)
{
Money tempMoney;
tempMoney = aMoney;
return tempMoney;
}

Money bMoney = lastYear(aMoney );
bMoney.output( );

I got warning when compiling. But running actually went through and
output() printed out the "correct" value, the same value as aMoney.
Based on what you said above, I would expect bMoney.output() prints out
garbage, since bMoney binds to a non-existent object. Could you give me
more help?


It is possible that bMoney.output() prints out the expected value, or
just as possible that it prints out garbage, or just as possible that
it sends an e-mail to your girlfriends' husband telling him what you
did last weekend <g>. This is called "undefined behavior", and
ANYTHING is possible when you have undefined behavior.

--
Bob Hairgrove
No**********@Ho me.com
Dec 13 '05 #9
Xiaoshen Li schrieb:
ni*****@microso ft.com wrote:
In this case, tempMoney is still destroyed and the reference
returned by the function is bound to a non-existent object.
Unlike in Java, the existence of a reference has no impact on
the lifetime of the referenced object. Likewise, a pointer does
not affect the lifetime of the pointee. It's up to you to make
sure there are no dangling references or pointers.

I became so interested in seeing this so I wrote code to test it. BUT,
the results is not what you said. (I truely believe you are correct!).
With following function:

Money& lastYear(Money aMoney)
{
Money tempMoney;
tempMoney = aMoney;
return tempMoney;
}

Money bMoney = lastYear(aMoney );


Here you are copying the object into another object so that...
bMoney.output() ;
This operates on a completly valid object.
I got warning when compiling. But running actually went through and
output() printed out the "correct" value, the same value as aMoney.
Based on what you said above, I would expect bMoney.output() prints out
garbage, since bMoney binds to a non-existent object. Could you give me
more help?


Try this:

Money &bMoney = lastYear(aMoney );
bMoney.output() ;

bMoney will refer to the local variable in lastYear which is no more
valid. You get undefined behavier. "undefined" means here that
everything could happen, including that the "correct" values are printed
out in the case that these values are not overwritten yet.

Thomas
Dec 13 '05 #10

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

Similar topics

8
1703
by: varois83 | last post by:
Hi I am a newbie and struggling with my guestbook validation process. I have found the following function online to check the length of a form field. <?php function checkLength($string, $min, $max) { $length = strlen ($string); if (($length < $min) || ($length > $max)) {
11
18332
by: eddie wang | last post by:
The following code with formatnumber function returns me the following code. Why? Thanks. <td align="right"><Font class=content4><%=formatNumber(ars.Fields("SOLD_AMOUNT"),2)%></td> Microsoft VBScript runtime error '800a000d' Type mismatch: 'formatNumber'
4
11366
by: octavio | last post by:
Hello members of the comp.lang.c newsgroup. Please I need you help on the following one. Compiling the simple code I'm getting this error message. Why ? Please what's the correct type of the fb function ? Thank You. Octavio and.c:15: attention : type mismatch with previous implicit declaration and.c:11: attention : previous implicit declaration of `fb'
18
3137
by: ben.carbery | last post by:
Hi, I have just written a simple program to get me started in C that calculates the number of days since your birthdate. One thing that confuses me about the program (even though it works) is how global variables and function returns work... For example, I have a global array "char datestring;" which is defined in the function speakdate. speakdate just converts a set of integers (date variables) to a string.
7
3722
by: divya | last post by:
What is an equivalent TimeSerial() function of VBscript in the Java Script?? I have two variables hour and minutes. Timeserial(hour,minutes) returns the time hour : minutes. But I want to do similar thing using the javascript .Can anybody help me out with the procedure. Divya.
0
1197
by: p.lavarre | last post by:
Now at http://pyfaq.infogami.com/suggest we have: FAQ: How do I declare that CTypes function returns void? A: c_void = None is not doc'ed, but is suggested by: <class 'ctypes.c_void_p'> Remembering c_void = c_int from K&R C often works, but if you say a restype is c_int, then doctest's of that call will print an int, yuck. If you say the restype is None, then those doctest's work: they print
2
2146
by: james_027 | last post by:
hi everyone, I am now in chapter 5 of Dive Into Python and I have some question about it. From what I understand in the book is you define class attributes & data attributes like this in python class Book: total # is a class attribute
5
2642
by: Travis | last post by:
I am using a function that returns a const char * that is usually a word, etc. How can I check to see if what it returns is empty? I tried if (function() == "") and (function() == NULL) and (function() == '/0'). But then I see that the those if statements are flagging true when the function returns back a char * or no length
2
4907
by: jpr | last post by:
I have 2 classes saved as 2 different java files.(eg- class ABC.java & PQR.java) ->ABC.java classABC extends JTextField { ABC(int i) { super(i); ...
0
9711
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9593
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
10595
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
10343
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
10335
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
9169
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...
0
6862
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
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.