Switch to full style
For C/C++ coders discussions and solutions
Post a reply

operator int()

Fri Nov 07, 2008 6:08 pm

I got a question. I have a class B that has this method:
Code:
operator int()
{
std::cout << "int()" << std::endl;
return i;
}


I dont know exactly how it works but every time I call this method:

Code:
int foo1(B b)
{
return b;
}


it prints int().



Re: operator int()

Fri Nov 07, 2008 6:09 pm

Implicit class conversion to another type using operator overloading.
The C++ compiler makes a best-guess effort at creating a successful
compile by looking at the existing class methods and the type the code
is expecting and then creating the necessary code as output. This is,
IMO, one of the coolest features of C++ (you can even "typecast" between
classes!) but, occasionally, one of the more annoying ones should you
depend on the feature too much. That is, you can "see" a clear path to
the implicit solution but the compiler insists there isn't one.

Post a reply
  Related Posts  to : operator int()
 What is the % operator     -  
 Using the ? Operator     -  
 What is Operator Overloading? !!!     -  
 Sizeof Operator     -  
 Object without new Operator     -  
 stream operator     -  
 trinary operator     -  
 operator overloading     -  
 shift operator in java     -  
 unary operator overloading     -  

Topic Tags

C++ OOP