cpp types

Conversion Operator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class MyIntegerWrapper {
private:
int value;

public:
// Constructor
MyIntegerWrapper(int val) : value(val) {}

// Conversion operator to int
operator int() const {
return value;
}
};

int main() {
MyIntegerWrapper myObj(42);

// Implicit conversion using the conversion operator
int intValue = myObj;
std::cout << "Implicit Conversion: " << intValue << std::endl;

// Explicit conversion using static_cast
double doubleValue = static_cast<double>(myObj);
std::cout << "Explicit Conversion: " << doubleValue << std::endl;

return 0;
}