J
joel.winteregg
Hi all,
I "learnt" C++ a few years ago and then i have been using C for a
couple of month and i'm now trying to get back to the ++ world (but
with some troubles...). I have some problem to understand why a "new"
return a pointer and not a reference. Here are explanations:
/* to get my object in heap */
MyClass* objectPtr = new MyClass();
If i want to handle my object using a reference i will have to do
something like this:
MyClass& objectRef = *objectPtr;
/* or all in one */
MyClass& objectRef = *(new MyClass());
Why the use of "new" wasn't done to get reference and malloc to get
pointers ? wouldn't it be easier ?
I also have an other question about function call using references.
During my search i have been reading this post:
http://groups.google.com/group/comp...a954a?lnk=st&q=&rnum=7&hl=en#0436bcd62faa954a
which confuse me a lot. Is it right that a function which return an
object ref will return it using the copy constructor (a copy of it ) ?
MyClass& GetMyClass() { return myObject; }
MyClass& myObj = GetMyClass();
I thought that the "return MyClass" statement would return the ref of
"myObject" and not a copy of it !! (Hope the object was allocated using
new and not statically ;-) )
I would do it by copy, like this:
MyClass GetMyClass() { return myObject; }
/* object statically allocated */
MyClass myObj = GetMyClass();
Thanks a lot for your help !!
Joël
I "learnt" C++ a few years ago and then i have been using C for a
couple of month and i'm now trying to get back to the ++ world (but
with some troubles...). I have some problem to understand why a "new"
return a pointer and not a reference. Here are explanations:
/* to get my object in heap */
MyClass* objectPtr = new MyClass();
If i want to handle my object using a reference i will have to do
something like this:
MyClass& objectRef = *objectPtr;
/* or all in one */
MyClass& objectRef = *(new MyClass());
Why the use of "new" wasn't done to get reference and malloc to get
pointers ? wouldn't it be easier ?
I also have an other question about function call using references.
During my search i have been reading this post:
http://groups.google.com/group/comp...a954a?lnk=st&q=&rnum=7&hl=en#0436bcd62faa954a
which confuse me a lot. Is it right that a function which return an
object ref will return it using the copy constructor (a copy of it ) ?
MyClass& GetMyClass() { return myObject; }
MyClass& myObj = GetMyClass();
I thought that the "return MyClass" statement would return the ref of
"myObject" and not a copy of it !! (Hope the object was allocated using
new and not statically ;-) )
I would do it by copy, like this:
MyClass GetMyClass() { return myObject; }
/* object statically allocated */
MyClass myObj = GetMyClass();
Thanks a lot for your help !!
Joël