Declaration of operator function inside struct

78 views Asked by At

I was reading this document for templates:

An Idiot's Guide to C++ Templates - Part 2

I came across one definition that I did not understand:

struct Currency
{
  int Dollar;
  int Cents;

  operator double()
  {
    return Dollar + (double)Cents/100;
  }
};

It involves the definition of the operator double() function inside the struct body.

What exactly is this, and what does it do?

At first, I thought this was a functor, but a functor definition looks like this:

int operator ()

1

There are 1 answers

0
Ted Lyngmo On BEST ANSWER

The operator double() makes an instance of Currency implicitly convertible to double. Here are two examples where operator double() is used:

Currency cur{1, 2};

double d = cur; // this works, d is now 1.02

std::cout << cur << '\n'; // and even this (and prints 1.02)