Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a user defined type to primitive type?

Tags:

c++

Let's say we have a class called Complex which represents a complex number. I want to convert this object to a double object.

The other way around i can do by implementing a copy ctor in Complex:
Complex(const double &d);

However, i can't implement i copy ctor in double which will receive a Complex.

How do i do this? I know there is a way with operator overloading, but i couldn't find how.
Eventually i want the this line will compile:
Complex c;
(double)c;

Thanks!!

like image 614
Asher Saban Avatar asked Sep 30 '10 17:09

Asher Saban


People also ask

How can you convert user-defined data type into primitive data type?

C++ Now, this function converts a user-defined data type to a primitive data type. For Example, the operator double() converts a class object to type double, the operator int() converts a class type object to type int, and so on.

How you will convert an object data type to a basic data type?

You convert an Object variable to another data type by using a conversion keyword such as CType Function.

What is user-defined type conversion?

For more information, see Standard Conversions. User-defined conversions perform conversions between user-defined types, or between user-defined types and built-in types. You can implement them as Conversion constructors or as Conversion functions.

How many types are there in user-defined conversion?

There are two types of user-defined conversions: Conversion constructors and conversion functions.


2 Answers

Implement a conversion operator on your Complex class:

class Complex
{
 // ...
  operator double() const
  { 
    double ret = // magic happens here
    return ret;
  }
};

If for whatever reason you don't want to muck about with this, you can provide a global conversion function:

double convert_to_double(const Complex& rhs)
{ 
  double ret = // magic happens
  return ret;
}
like image 110
John Dibling Avatar answered Nov 03 '22 17:11

John Dibling


The proper way of doing this is adding a conversion operator to your class.

class myclass {    
public:    
    operator double() const
    {
        return _mydouble;
    }
...
};

and used like this:

myclass c;
double d = c; // invokes operator double
like image 45
Idan K Avatar answered Nov 03 '22 18:11

Idan K