Topic: Why direct-initialization on casts??


Author: Stefan Neis <neis@cdc.informatik.th-darmstadt.de>
Date: 1998/02/05
Raw View
 Hi,

What is the reason for static_cast and type conversion to use
direct-initialization instead of copy-initialization? For me, the resulting
actions of compilers seem to be completely illogical. Consider a small
example which compiles fine with compilers compliant to the ANSI-draft:

class B;
class A{
public:
  A();
  operator B() const;
  operator int *() const;
};

class B{
public:
  B(const int *);
};

void test_cast(B);

main()
{
  test_cast(A());
}

Note that in 'test_cast(A())', the A constructed using the empty
constructor will automatically be converted to a B. Since
copy-initialization is used, the matching operator B() is applied and that
is it.

However, if I try to make this cast explicit for the sake of compatibility
with some older compiler (SunPro 4.1) by writing 'test_cast(B(A()))' or
'test_cast(static_cast<B>(A()))' or whatever, the program suddenly fails to
compile on ANSI-conformant compilers. The reason for this is quite obvious:
Since casts involve direct-initialization, a contructor of B has to be
applied, and then, the compiler has now way to decide, whether to apply
'operator B()' and the copy constructor or 'operator int *()' and
'B(const int*)'. But what is the reason for mandating direct-initialization
in such situations ??

 Best,
  Stefan Neis

P.S.: Some experiments with this situation seem to prove, that MSVC is
 using direct-initialization for function return -- contrary to the
 ANSI-draft. However, gcc-2.8 works as expected.
--
This message was composed on a Micro$oft-free system.


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]