473,553 Members | 2,957 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How Methods Return Objects

I'd like to know what goes on under the hood when methods return
objects. Eg, I have a simple Point class with two members _x and _y.
It's constructor, copy constructor, assignment operator and additon
operator (which returns another Point object, and which my question is
about) are as follows:

Point::Point(in t x, int y) :
_x(x),
_y(y) { }

Point::Point(co nst Point& p) {
_x = p._x;
_y = p._y;
}

Point& Point::operator =(const Point& p) {
_x = p._x;
_y = p._y;
return (*this);
}

Point Point::operator +(const Point& p) const {
Point ret(_x + p._x, _y + p._y);
return ret;
}

What happens when operator+ returns the temporary Point object that it
creates?

Does it use the copy constructor to create a copy of the temporary
variable "ret"? Is ret destroyed after that?

If not, how does it return a Point object?

Also, why is that "new" never comes into play? How can the compiler
know beforehand how many Point objects will be created via operator+?
Is it because such objects must exist in statements like:

Point p3 = p1 + p2;

I know this is a simple point, but I'm confused nonetheless.

Thanks for any clarification,
cpp

Jul 22 '05 #1
25 4119
"cppaddict" <he***@hello.co m> wrote...
I'd like to know what goes on under the hood when methods return
objects. Eg, I have a simple Point class with two members _x and _y.
It's constructor, copy constructor, assignment operator and additon
operator (which returns another Point object, and which my question is
about) are as follows:

Point::Point(in t x, int y) :
_x(x),
_y(y) { }

Point::Point(co nst Point& p) {
_x = p._x;
_y = p._y;
I wonder why you didn't use initialisation here...
}

Point& Point::operator =(const Point& p) {
_x = p._x;
_y = p._y;
return (*this);
}

Point Point::operator +(const Point& p) const {
Point ret(_x + p._x, _y + p._y);
return ret;
}

What happens when operator+ returns the temporary Point object that it
creates?

Does it use the copy constructor to create a copy of the temporary
variable "ret"? Is ret destroyed after that?
Generally speaking, yes. Since 'ret' is an automatic variable, it will
be destroyed right after the function ends (right after the 'return'
statement). In order for the Point object to exist after the function
has finished but before its value is used elsewhere, a temporary one
is created using the copy constructor.

If not, how does it return a Point object?

Also, why is that "new" never comes into play?
How do you know it doesn't? Creation of a temporary _might_ be internally
done using some kind of special form of 'new'. It's not defined, AFAIK.
Where the temporary is created and how is, well, unimportant. At least
from the langauge standpoint.
How can the compiler
know beforehand how many Point objects will be created via operator+?
Every time it has to call operator+ function, another Point object is
potentially created.
Is it because such objects must exist in statements like:

Point p3 = p1 + p2;


The compiler is allowed to forgo creation of a temporary in this case
and instead generate code so that when you return the 'ret' from the
function operator+, it is used to directly initialise the 'p3' object.

You might find all that in good books. Or by looking at the code (yes,
it's usually assembly language) that the compiler generates from your
C++ source.

Victor
Jul 22 '05 #2
Point::Point(co nst Point& p) {
_x = p._x;
_y = p._y;


I wonder why you didn't use initialisation here...


I should have. Thanks for pointing that out.

Thanks for you other explanations as well.

cpp
Jul 22 '05 #3

cppaddict wrote:
Point::Point (const Point& p) {
_x = p._x;
_y = p._y;


it is unwise to use a leading underscore in a variable name, although in
this case, not technically illegal (17.4.3.1.2).

mark

Jul 22 '05 #4
>it is unwise to use a leading underscore in a variable name, although in
this case, not technically illegal (17.4.3.1.2).

mark


I was under the (mistaken) impression that this was a standard way to
indicate member variables. Do you know what leading underscores are
reserved for? Also, what is the standard way to indicate a member
variable -- trailing underscore?

Thanks,
cpp

Jul 22 '05 #5
"cppaddict" <he***@hello.co m> wrote...
it is unwise to use a leading underscore in a variable name, although in
this case, not technically illegal (17.4.3.1.2).

mark


I was under the (mistaken) impression that this was a standard way to
indicate member variables. Do you know what leading underscores are
reserved for? Also, what is the standard way to indicate a member
variable -- trailing underscore?


There is no "standard way" to indicate anything. The Standard prohibits
the use of reserved [by the implementation] names. Such names include
names with double underscores and names that begin with an underscore and
a capital letter.

I am, of course, picking at your use of the word "standard" here. Not
that I have ill will, but traditionally "standard" here means required
or defined by the Standard Document. You might want to use the word
"convention al", as in "what is the conventional way to indicate..."

As to the accepted conventions, there are several. The one I see used
the most is the prefix 'm_' for non-static data members and 's_' for
static data members. Leading underscores, just like trailing underscores,
are not easy to read, that's why most people try to avoid them, I guess.

Victor
Jul 22 '05 #6
On Fri, 30 Jul 2004 03:18:57 GMT, cppaddict <he***@hello.co m> wrote:
it is unwise to use a leading underscore in a variable name, although in
this case, not technically illegal (17.4.3.1.2).

mark


I was under the (mistaken) impression that this was a standard way to
indicate member variables. Do you know what leading underscores are
reserved for? Also, what is the standard way to indicate a member
variable -- trailing underscore?

Thanks,
cpp


Its a good way to indicate member variables. I don't understand why some
people claim its dangerous (I am aware of when underscore use is illegal).
Perhaps Mark could justify his claim?

john
Jul 22 '05 #7
John Harrison wrote:

On Fri, 30 Jul 2004 03:18:57 GMT, cppaddict <he***@hello.co m> wrote:
it is unwise to use a leading underscore in a variable name, although in
this case, not technically illegal (17.4.3.1.2).

mark


I was under the (mistaken) impression that this was a standard way to
indicate member variables. Do you know what leading underscores are
reserved for? Also, what is the standard way to indicate a member
variable -- trailing underscore?

Thanks,
cpp


Its a good way to indicate member variables. I don't understand why some
people claim its dangerous (I am aware of when underscore use is illegal).
Perhaps Mark could justify his claim?

john


Some say that it's hard to remember the exact rules (never use a leading
underscore followed by an uppercase letter; never use a double underscore;
in the global scope, don't use a leading underscore regardless of the
symbol that follows). There is some potential for an error here,
especially due to code maintenance by those who don't read too much
into language details.
This potential is arguably smaller when using a trailing underscore
instead.

I don't mind it either way (and much prefer them over any alternative),
but in my limited scope the trailing underscore has become more
conventional. I've got used to it and love it.

Denis
Jul 22 '05 #8

"Denis Remezov" <fi************ ***@yahoo.remov ethis.ca> wrote in message
news:41******** *******@yahoo.r emovethis.ca...
John Harrison wrote:

On Fri, 30 Jul 2004 03:18:57 GMT, cppaddict <he***@hello.co m> wrote:
> it is unwise to use a leading underscore in a variable name, although in> this case, not technically illegal (17.4.3.1.2).
>
> mark

I was under the (mistaken) impression that this was a standard way to
indicate member variables. Do you know what leading underscores are
reserved for? Also, what is the standard way to indicate a member
variable -- trailing underscore?

Thanks,
cpp


Its a good way to indicate member variables. I don't understand why some
people claim its dangerous (I am aware of when underscore use is illegal). Perhaps Mark could justify his claim?

john


Some say that it's hard to remember the exact rules (never use a leading
underscore followed by an uppercase letter; never use a double underscore;
in the global scope, don't use a leading underscore regardless of the
symbol that follows). There is some potential for an error here,
especially due to code maintenance by those who don't read too much
into language details.
This potential is arguably smaller when using a trailing underscore
instead.

I don't mind it either way (and much prefer them over any alternative),
but in my limited scope the trailing underscore has become more
conventional. I've got used to it and love it.

Denis


I guess I prefer a leading underscore because its the first thing you see
when you read a name. I guess the same reason you often see m_something but
never something_m.

But yes, beauty is in the eye of the beholder.

john
Jul 22 '05 #9

"John Harrison" <jo************ *@hotmail.com> wrote in message
news:opsbxo1yjt 212331@andronic us...
On Fri, 30 Jul 2004 03:18:57 GMT, cppaddict <he***@hello.co m> wrote:
Its a good way to indicate member variables. I don't understand why some
people claim its dangerous (I am aware of when underscore use is illegal).
Perhaps Mark could justify his claim?


Because they are used by the compiler implementations too.
To quote Herb Sutter here - "Try to avoid names with leading underscores.
Yes, I've habitually used them, and yes, popular books like "Design
Patterns" (Gamma et al) do use it... but the standard reserves some
leading-underscore identifiers for the implementation and the rules are hard
enough to remember (for you and for compiler writers!) that you might as
well avoid this in new code. (Since I'm no longer allowed to use leading
underscores as my "member variable" tag, I'll now use trailing
underscores!)"

This simple program on MS VC 7.0 cribs for ambiguous symbol -

#include <map>
using namespace std;
class _Tree{
};

int main()
{
_Tree t;
}

-Sharad

Jul 22 '05 #10

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

Similar topics

99
5826
by: David MacQuigg | last post by:
I'm not getting any feedback on the most important benefit in my proposed "Ideas for Python 3" thread - the unification of methods and functions. Perhaps it was buried among too many other less important changes, so in this thread I would like to focus on that issue alone. I have edited the Proposed Syntax example below to take out the...
0
1194
by: Marcin 'Qrczak' Kowalczyk | last post by:
I made a bridge between my language Kogut <http://qrnik.knm.org.pl/~qrczak/kogut/kogut.html> and Python, which gives my language instant access to Python libraries. There is a minor annoyance in the C API: the __unicode__ method does not have its own slot in type objects, it's not treated specially like __str__. /* XXX As soon as we have...
14
6294
by: Joe Fallon | last post by:
I am trying to build a Data Access Layer for a SQL Server back end. My class has a number of methods in it. The constructor takes a connection string. I currently have to instantiate an object in order to use one of my methods. So I end up doing this quite a lot in my app. If I change all of the methods to be Shared does that mean I can...
12
5520
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. Foo = function(type) { this.num = 0; this.type = type this.trigger(); } Foo.prototype.trigger = function() {
3
2311
by: Michael Maes | last post by:
Hi, We have a windows service passing objects to a client application by remoting. The windows service is started and running successfully. * When the client app is running on the same machine as the windows service (W2K3) every method gets executed successfully. * When the client app is running on a different machine (XP SP2), some...
11
3030
by: Aflj | last post by:
This code won't compile (two compilers tried, gcc and VC++, both of recent versions, but I don't remember them exactly): class C1 { public: void M1(int i) {} }; class C2: public C1
10
105060
by: r035198x | last post by:
The Object class has five non final methods namely equals, hashCode, toString, clone, and finalize. These were designed to be overridden according to specific general contracts. Other classes that make use of these methods assume that the methods obey these contracts so it is necessary to ensure that if your classes override these methods, they...
2
1769
by: fgh.vbn.rty | last post by:
Hi, I'm not sure if i'm asking the question correctly but anyway here it is. Say I have 3 classes - class A, class B, class R. 1) A and B are the building blocks and R is like a repository that stores objects of A and B. 2) A is at the lowest level and should "know about" only other As. B should know only about As and other Bs.
1
1976
by: Felix T. | last post by:
I have a class called Interval(type.ObjectType) that is supposed to mimic closed mathematical intervals. Right now, it has a lot of methods like this: def __add__(self,other): if type(other) in Numerical: return Interval(self.lower_bound+other, self.upper_bound +other) else: return Interval(self.lower_bound+other.lower_bound,
0
7568
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...
0
7492
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...
0
7772
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. ...
0
8007
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...
1
7526
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...
0
7852
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6109
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...
1
5409
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...
1
1990
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.