On 12/13/2015 1:38 PM, JiiPee wrote:
> [snip]
> Now, If I create an object and initialize, normally we do:
>
> 1)
> Person driver("John", "Smith");
>
> But we could also do:
> 2)
> Person driver;
> driver.setFirstName("John");
> driver.setsecondName("Smith");
>
> Now, I know everybody says 1) should be done. And I know the benefits...
> but.. am I also right the 2) tells more accurately
> which parameter you are setting? In 1) we cannot be sure (without
> checking the documentation) that which one is the first name
> and which one is the second name.
You can name the arguments to a constructor in many ways.
One way is to use the FAQ's "named parameters idiom". Another way is to
use the Boost parameters library (but it's too complex for me, although
at one time I drooled when discovering the preprocessor hacks in there).
And a third way can be to simply name special argument types:
<code>
#include <string>
#include <utility> // std::move
using namespace std;
template< class Value, class Type_id_type >
class Box
{
private:
Value v_;
public:
auto ref() -> Value& { return v_; }
Box( Value v ): v_( move( v ) ) {}
};
using First_name = Box< wstring, struct First_name_id >;
using Last_name = Box< wstring, struct Last_name_id >;
class Person
{
private:
wstring first_name_;
wstring last_name_;
public:
auto first_name() const -> wstring { return first_name_; }
auto last_name() const -> wstring { return last_name_; }
void set( First_name value ) { first_name_ = move(
value.ref() ); }
void set( Last_name value ) { last_name_ = move(
value.ref() ); }
Person( First_name first_name, Last_name last_name )
: first_name_( move( first_name.ref() ) )
, last_name_( move( last_name.ref() ) )
{}
};
#include <iostream>
auto main() -> int
{
auto x = Person( First_name( L"Jii" ), Last_name( L"Pee" ) );
wcout << x.first_name() << " " << x.last_name() << "\n";
}
</code>
> [snip]
> This is what i have been struggled many times.
Well, I hope the above gave you some ideas! ;-)
Cheers & hth.,
- Alf