Re: pointer versus reference in constructors
From: Jeff Schwab (jeffplus_at_comcast.net)
Date: 05/29/04
- Next message: Daniel T.: "Re: Assignment Operator in ABC"
- Previous message: Phlip: "Re: Correct me if I'm wrong here C++ guys."
- In reply to: Daniel T.: "Re: pointer versus reference in constructors"
- Next in thread: E. Robert Tisdale: "Re: pointer versus reference in constructors"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 29 May 2004 14:09:28 -0400
Daniel T. wrote:
> In article <10b54proobcjl52@corp.supernews.com>,
> "johny smith" <princetonharvard@charter.net> wrote:
>
>
>>I never really know if I should use references or pointers for constructors.
>>
>>Can anyone give me some guidance on when to use what?
>>
>>My back ground is C, so I tend to use pointer notation, but really don't
>>know what the advantage of the reference it.
>>
>>Thanks alot.
>>
>>ex. of two constructors
>>
>>Car( Engine* engine )
>>
>> or,
>>
>>Car( Engine& engine)
>
>
> The answer depends on how you expect Car to be used. Do you want clients
> to be able to do:
>
> Car myCar( new Engine );
>
> If so, then the pointer c_tor would be best (obviously here the Car must
> take control of the lifetime of the engine passed in.) If clients should
> be able to do:
>
> Engine e;
> Car myCar( e );
>
> then the reference c_tor is best... (here the car is not taking control
> of the lifetime of the object passed in, it is either sharing the
> engine, or making a copy of the engine.)
I'm not sure I like the
Car car( new Engine );
idea, since it's unclear without further documentation who is
responsible for deleting the engine, and I find this:
Car car( *new Engine );
equally readable. If the idea is to be able to support whichever style
the client prefers, though, then it should be noted that the two styles
presented here aren't mutually exclusive; it's entirely possible to
provide constructors for both usage models, perhaps using an extra level
of inheritance to encapsulate the commonality of the constructors:
Car( Engine* engine ): Car_base( *engine ) { }
Car( Engine& engine ): Car_base( engine ) { }
Of, if you like:
Car( Engine* engine ): Car_base( engine ) { }
Car( Engine& engine ): Car_base( &engine ) { }
> IN GENERAL: Whenever you aren't sure which interface would be better
> (and this is certainly an interface issue) always look at the problem
> from the perspective of the clients of the class, *not* the
> implementation of the class.
Right on.
- Next message: Daniel T.: "Re: Assignment Operator in ABC"
- Previous message: Phlip: "Re: Correct me if I'm wrong here C++ guys."
- In reply to: Daniel T.: "Re: pointer versus reference in constructors"
- Next in thread: E. Robert Tisdale: "Re: pointer versus reference in constructors"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|