Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   copying object from reference (http://www.velocityreviews.com/forums/t743913-copying-object-from-reference.html)

techieV 02-21-2011 06:20 AM

copying object from reference
 
Hi,

I am struck at below problem while working on a issue.

Is this correct in cpp - sending a reference to an object in a
function call and while receiving receive it in a local object? The
real call to func1 is - someObj.func1( getClass1Obj()); and this 'Get'
function returns a reference to const object.

function prototype -
class someClass
{
public:
func1( Class1 object);
}

and calling this function as - someObj.func1( &class1obj);

Thank you in advance.

PhilipDexter 02-21-2011 07:18 AM

Re: copying object from reference
 
On Feb 21, 7:20*am, techieV <techie.v...@gmail.com> wrote:
> Hi,
>
> I am struck at below problem while working on a issue.
>
> Is this correct in cpp - sending a reference to an object in a
> function call and while receiving receive it in a local object? The
> real call to func1 is - someObj.func1( getClass1Obj()); and this 'Get'
> function returns a reference to const object.
>
> function prototype -
> class someClass
> {
> * * *public:
> * * *func1( Class1 object);
>
> }
>
> and calling this function as - someObj.func1( &class1obj);
>
> Thank you in advance.


I believe you'll get an error that you cannot convert a const ref to a
ref. Other than that it will work, just make sure you have a copy
constructor!

Marcel Müller 02-21-2011 08:01 AM

Re: copying object from reference
 
techieV wrote:
> I am struck at below problem while working on a issue.
>
> Is this correct in cpp - sending a reference to an object in a
> function call and while receiving receive it in a local object?


Yes. This will implicitly invoke the copy constructor (as long as it
exists).

> The
> real call to func1 is - someObj.func1( getClass1Obj()); and this 'Get'
> function returns a reference to const object.


However, the call to getClass1Obj() implies that it might be a factory
function. And in this case, it might be a logical error from the
applications point of view to copy the result. If the application code
is well designed, it has no (visible) copy constructor for Class1 in
this case. And then you will get a compiler error.


> function prototype -
> class someClass
> {
> public:
> func1( Class1 object);
> }
>
> and calling this function as - someObj.func1( &class1obj);


This is an error. The &-Operator returns a pointer and func1 takes an
object.
(Of course, unless Class1 can be implicitly constructed from this
pointer. But this is unlikely.)


Marcel


All times are GMT. The time now is 10:32 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.