c++ - User-defined conversion operator to inaccessible base class -
why not allow user-defined conversion base class (or reference it) when base inacessible: protected or private?
when there class d , public base b, there implicit rule bind references b (b& or b&&, possibly cv-qualified) objects of class d, user-defined conversion b& doesn't make sense. when base class protected or private, implicit rule not applicable anymore. why not allow use user-defined conversion b& (or const b& or b&& etc.)?
it allowed, nothing in standard prohibits this. states such conversion operator never used. [class.conv.fct]/1:
a conversion function never used convert (possibly cv-qualified) object (possibly cv-qualified) same object type (or reference it), (possibly cv-qualified) base class of type (or reference it), or (possibly cv-qualified) void.
overload resolution prefer base class constructor on conversion operator, , conversion operator never called, unnecessary implicit conversions. access checking done after overload resolution, the conversion operator never considered.
struct b { b() = default; b(const b&) = default; b& operator=(const b&) = default; }; struct d : protected b { operator b() { return *this; } }; int main() { d d; b b = d; // (1) b = d; // (2) } for (1), copy constructor b(const b&) better match converting d b using conversion operator ([over.match.ctor]/1), constructor chosen. access checked, , because b's copy constructor protected, doesn't compile.
for (2) exact same thing. b& operator=(const b&) chosen overload resolution because better match call user defined conversion operator of d. b's assignment operator protected, , can't access outside of d, , code doesn't compile.
that's how overload resolution works, far know reason.
Comments
Post a Comment