Cpp - Overload int() operator

Introduction

You can assign an object to a built-in value, which is attempted in this code:

Counter gamma(18); 
int delta = gamma; 
cout << "delta : " << delta  << "\n"; 

C++ provides conversion operators that can be added to a class to specify how to do implicit conversions to built-in types.

Demo

#include <iostream> 
   //from   www.j a  va 2s  .  c  o m
class Counter 
{ 
public: 
    Counter(); 
    ~Counter() {} 
    Counter(int newValue); 
    int getValue() const { return value; } 
    void setValue(int newValue) { value = newValue; } 
    operator unsigned int(); 
private: 
    int value; 
}; 
   
Counter::Counter(): 
value(0) 
{} 
 
Counter::Counter(int newValue): 
value(newValue) 
{} 
 
Counter::operator unsigned int() 
{ 
    return (value); 
} 
   
int main() 
{ 
    Counter epsilon(19); 
    int zeta = epsilon; 
    std::cout << "zeta: " << zeta << std::endl; 
    return 0; 
}

Result