Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion Operators in C++

Please help me understand how exactly the conversion operators in C++ work. I have a simple example here which I am trying to understand, though it is not very clear how the conversion actually happens by the compiler.

class Example{ public:     Example();     Example(int val);     operator unsigned int();     ~Example(){} private:     int itsVal; };  Example::Example():itsVal(0){}  Example::Example(int val):itsVal(val){}  Example::operator unsigned int (){     return (itsVal); }  int main(){     int theInt = 5;     Example exObject = theInt; // here      Example ctr(5);     int theInt1 = ctr; // here     return 0; } 
like image 600
Zuzu Avatar asked Sep 05 '09 15:09

Zuzu


People also ask

What is a conversion operator?

A conversion operator, in C#, is an operator that is used to declare a conversion on a user-defined type so that an object of that type can be converted to or from another user-defined type or basic type. The two different types of user-defined conversions include implicit and explicit conversions.

What are conversion operators in C++?

Conversion Operators in C++ C++ supports object oriented design. So we can create classes of some real world objects as concrete types. Sometimes we need to convert some concrete type objects to some other type objects or some primitive datatypes. To make this conversion we can use conversion operator.

How many types of conversion are there in C?

There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion.

What is type conversion in C language?

In C programming, we can convert the value of one data type ( int, float , double , etc.) to another. This process is known as type conversion.


1 Answers

You can walk through that code with a debugger (and/or put a breakpoint on each of your constructors and operators) to see which of your constructors and operators is being invoked by which lines.

Because you didn't define them explicitly, the compiler also created a hidden/default copy constructor and assignment operator for your class. You can define these explicitly (as follows) if you want to use a debugger to see where/when they are being called.

Example::Example(const Example& rhs) : itsVal(rhs.itsVal) {}  Example& operator=(const Example& rhs) {     if (this != &rhs)     {         this->itsVal = rhs.itsVal;     }     return *this; } 
like image 168
ChrisW Avatar answered Oct 14 '22 22:10

ChrisW