1 Replies - 3904 Views - Last Post: 13 October 2009 - 07:38 AM Rate Topic: -----

#1 ethereal1m  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 227
  • Joined: 30-June 09

Convert between user define data type and basic data type

Post icon  Posted 13 October 2009 - 01:23 AM

Greetings experts,
I still in the process of understanding concept of data conversion using operator overloading.

I have a class named Int that acts like an int and does addition calculation.

Here is the code:

#include <iostream>
using namespace std;
#include <stdlib.h>

class Int {
	private:
	int var;

	public:
	Int(): var(0)
	{}
	Int(int in): var(in)
	{}
	
	Int operator + (Int v) {
		long double temp;

		temp=long double(var)+long double(v.var);
		cout<<" temp is "<<temp<<endl;
		if (temp>2147483648)
		{
			cout<<" Number is too big ";
			exit(1);
		}
		return static_cast<int>(temp);
	}
	void getVal() {
		cout<<"Enter var "<<endl;
		cin>>var;
	}
	void showVal() {
		cout<<"var is "<<var<<endl;
	}
};

void main() {
	Int v1, v2, v3;
	v1.getVal();
	v2.getVal();
	
	v3=v1+v2;
	v3.showVal();

}





Question:
1. How come compiler doesn't complain when I do:
temp=long double(var)+long double(v.var);


in overloading + function. Since v.var is user defined Int and I try to convert it to long double, I expect compiler to fail it.
2. This statement actually will cause the compiler to fail:
temp=long double(var)+long double(v);


unless I add Int to int conversion to the class:
operator int()
{return var;}


How does float overloading function work? does it execute automatically every time a user defined Int variable is assigned to a basic data type?
3. Is:
long double(var)
same thing as:
static_cast<long double>(var)
?

Very much appreciated from ethereal1m

Is This A Good Question/Topic? 0
  • +

Replies To: Convert between user define data type and basic data type

#2 Shamayla  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 12
  • Joined: 09-October 09

Re: Convert between user define data type and basic data type

Posted 13 October 2009 - 07:38 AM

temp=long double(var)+long double(v.var);
This statement works because v is the User defined Int. v.var acesses the int var member item that you have declared in the class which is of basic type int not Int.
and the other statement fails to execute because you are trying to add an int to an Int.

Is:long double(var)same thing as:static_cast<long double>(var)?

yes it is....they are two different approches to do the same thing. the c approach and the c++ approach.


Do thank me if the post was helpful!
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1