guys here is the question
elow is the main function that creates the object of Mile and Kilometer classes. Write the definition of
Mile and Kilometer classes such that each statement in the main function is executed without any error.
Both classes must have default constructor that initialize the private data member of both classes with
zero.

B
main() {
float k = 10, k1, k2 = 30 ;
Kilometer km = k;
km.display(); //display the value of data member of km and also how many objects of
// Kilometer class has been created
k1 = km;
cout<<”k1 = ”<<km<<endl;
km = k2;
km.display();
float m = 13.5, m1;
Mile mile = 25;
Km = mile;
Km.display();
Kilometer km1;
km1 = 15;
mile = km1;
mile.display(); //display the value of data member of mile and also how many objects of
// Miles class has been created
m1 = mile;
cout<<”m1 = ”<<m1<<endl;

my question is very simple i know how to convert a usertype to float type etc but how do u covert a user defined type to basic type with out the use of a constructor il be glad if u ppl can help me

Recommended Answers

All 2 Replies

You can do it through a conversion operator :

class PositiveInteger{
  int i;
public:
  PositiveInteger(int i1 = 0 ) 
   { i = i1 <  0 ? 0 : i1; }
  operator int(){ return i; }
};
int main(){
 PositiveInteger i(23);
 int j = i; //convert to int
}
commented: I learned something. +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.