C++ program Data conversion class to class using operator in source class or using constructor in destination class.
Data
conversion class to class using operator in source class or using constructor
in destination class.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class invent2; //destination class declared
class invent1 //source class
{
int
code; //item code
int
items; //no.of items
float price; //cost of each item
public:
invent1(int a,int b,float c)
{
code=a;
items=b;
price=c;
}
void putdata()
{
cout<<"Code: "<<code<<"\n";
cout<<"Items: "<<items<<"\n";
cout<<"Value: "<<price<<"\n";
}
int
getcode()
{
return
code;
}
int
getitems()
{
return items;
}
int
getprice()
{
return price;
}
operator float()
{
return (items * price);
}
/*operator invent2() //invent1 to invent2
{
invent2 temp;
temp.code=code;
temp.value=price * items;
return temp;
} */
};
//End of source class
class invent2 //destination class
{
int
code;
float value;
public:
invent2()
{
code=0;
value=0;
}
invent2(int x, float y)
//constructor for
{ //initialization
code=x;
value=y;
}
void putdata()
{
cout<<"Code: "<<code<<"\n";
cout<<"Value: "<<value<<"\n";
}
invent2 (invent1 p) //
constructor for conversion
{
code=p.getcode();
value=p.getitems() * p.getprice();
}
};
int main()
{
invent1 s1(100,5,140.0);
invent2 d1;
float total_value;
clrscr();
/* invent1 to float */
total_value=s1;
/* invent1 to invent2 */
d1=s1;
cout<<"Product details - invent1
type"<<"\n";
s1.putdata();
cout<<"\nStock
value"<<"\n";
cout<<"Value =
"<<total_value <<"\n\n";
cout<<"Product details- invent2
type"<<"\n";
d1.putdata();
getch();
return 0;
}
OUTPUT
Product details - invent1 type
Code: 100
Items: 5
Value: 140
Stock value
Value = 700
Product details- invent2 type
Code: 100
Value: 700