c++ - Why I am not getting error in following code? -
#include <iostream> using namespace std; class { private: float data_member; public: a(int a); explicit a(float d); }; a::a(int a) { data_member = a; } a::a(float d) { data_member = d; } void test(a a) { cout<<"do nothing"<<endl; } int main() { test(12); test(12.6); //expecting compile time error here return 0; }
i expecting error int case ctor takes float value explicit. not getting error in vs 2010. please point me out if wrong understanding of keyword "explicit" in c++.
explicit a(float d);
does not think does. disables implicit conversion float
type a
. in short, disables implicit conversion wherein float implicitly converted object of a
. ex:
void dosomething(a obj){} dosomething(2.3);
it not disable implicit conversions allowed standard.
why compile?
test(12.6);
because float
parameter implicitly converted int
. happens behind scenes same as:
float = 12.6; int b = (int)a;
further, conversion constructor a::a(int a)
used create object of type a
passed method test()
.
why not compile if remove
explicit
?
without keyword explicit
conversion constructor a::a(float d)
available conversions , creates ambiguity because there 2 possible matches, when converting 12.6
object of type a
:
a::a(int a)
or
a::a(float d)
since none scores on other in terms of best match, compiler emits diagnostic of ambiguity.
Comments
Post a Comment