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.

#include<iostream>
using namespace std;

class MyInt {
	int val;
public:
	MyInt(int data) :
		val(data) {
	}
};

int main() {
	int a = 0;
	// create an object of class MyInt
	MyInt int_obj(10);
	// assign int_obj object to a
	a = int_obj;
	cout << a << endl;
	return 0;
}

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

../main.cpp"
../main.cpp: In function ‘int main()’:
../main.cpp:17:4: error: cannot convert ‘MyInt’ to ‘int’ in assignment
  a = int_obj;
    ^

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.

#include<iostream>
using namespace std;

class MyInt {
	int val;
public:
	MyInt(int data) :
		val(data) {
	}
	operator int() const {return val;}
};

int main() {
	int a = 0;
	// create an object of class MyInt
	MyInt int_obj(11);
	// assign int_obj object to a
	a = int_obj;
	cout << a << endl;
	return 0;
}

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