Search code examples
c++classoperator-overloadingassignment-operator

C++ classes: read value behave as different types


I want to create a class similar to this:

class MyTime {
public:
    int seconds;
    int useconds;

    /*** functions ***/
}

but which has the following behavior:

MyTime now;
double current_time = now; // returns double representing seconds

Is there a way to do this without have to define an asDoubleSeconds() function? Can I change the behavior by overloading the assignment operator somehow?

If not, is there a way to do something like this:

double current_time = double(now);

Solution

  • Yes, implement a user-defined conversion operator:

    class MyTime {
        // ...
    
        operator double() const;
    };
    
    MyTime::operator double() const {
        // compute and return a double
    }