Why are different conversion functions for int and const int allowed?

  • A+
Category:Languages

Why is the following allowed to be compiled in C++?

#include<iostream> using namespace std;  class mytest { public:         operator int()     {         return 10;     }      operator  const int()     {         return 5;     } };  int main() {     mytest mt;     //int x = mt;    //ERROR ambigious      //const int x = mt; //ERROR ambigious } 

Why does it make sense to allow different versions (based on constness) of the conversion operator to be compiled when their use always results in ambiguity?

Can someone clarify what I am missing here?

 


For conversion they're ambiguous; but you might call them explicitly. e.g.

int x = mt.operator int(); const int x = mt.operator const int(); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: