eriwik@student.chalmers.se wrote:
Quote:
s_amrollahi@yahoo.com wrote:
>
>
Quote:
>>josh نوشته است:
>>
Quote:
>>>Hi,
>>>
>>>if I've:
>>>
>>>class Date
>>>{
>> public:
>> Date(int m, int d, int y);
>>>}
>>>
>>>Date::Date(int m, int d, int y)
>>>{
>>>...
>>>}
>>>
>>>
>>>and then a class in which I've another object:
>>>class A
>>>{
>>>public:
>> A(int, int, int);
>>>
>>>private:
>> Date d;
>>>}
>>>A::A(int m, int d, int y) : d(m, d, y)
>>>{
>>>..
>>>}
>>>above is the only method to initialize objects?
>>>I can't do:
>>>A::A(int m, int d, int y)
>>>{
>> d(m, d, y);
>>>}
>>>
>>>Correct?
>>
>>Yes. Because Date has no Default Coonstructor, So it should be
>>initialized using member initialization list in A's constructor.
>
>
Yes, and even if you did have a default constructor it would still be
the best way to initialize the object, since if you didn't a
Date-object would first be created and then replaced with the one with
the right date set. Using an initializer-list you only create one
Date-object.
So efficiency is more important then, say readability? Because I'd find
this a little bit clearer
A a(Date(11,15,2006));
then this:
A a(11,15,2006);
Of course, I'm supposing that Date has a copy ctor, and A has a ctor
that looks like:
A::A(const Date &dateArgument) : d(dateArgument) {}
I think this also has the advantage of being a little more flexible if
for some reason Date gets new ctors. After all, you have a Date that is
a member of A, why expose, even as data initializers, the component
members of Date in A's ctor?
And even if Date didn't have a copy ctor, but had getters for m, d and y
(month, day and year might be better names?) I would still think that
having a ctor in A that looked like this would be clearer (even if it
was a lot less efficient):
A::A(const Date &dateArgument)
:
d(dateArgument.month(), dateArgument.day(), dateArgument.year())
{}
But then, your application and YMWV.
LR