how to convert object to int in c++? This is very basic c++ interview questions generally asked to freshers. In this tutorial we will learn how to assign any object to an basic type like int in c++ programming.

Let us write a very basic example. we will write c++ sample code which will not compile and based on the error we will modified the code to work as expected. learning from error remains longer.

The above code will not compile , it will error out as

So from error it is obvious that we need to define a int() conversion operator (casting operator)  inside class MyInt which will do the conversion.

Note:

The conversion operator (casting operator)  “operator int() { return val; }” do not require return type to be specified. 

Ref:

http://stackoverflow.com/questions/13730153/c-class-converting-object-to-integer




Related Contents to follow