Search code examples
c++typescastingtypecasting-operator

C++ Cast operator overload


I have a class with a single int member such as:

class NewInt {
   int data;
public:
   NewInt(int val=0) { //constructor
     data = val;
   }
   int operator int(NewInt toCast) { //This is my faulty definition
     return toCast.data;
   }
};

So when I call the int() cast operator I'd return data such as:

int main() {
 NewInt A(10);
 cout << int(A);
} 

I'd get 10 printed out.


Solution

  • A user-defined cast or conversion operator has the following syntax:

    • operator conversion-type-id
    • explicit operator conversion-type-id (since C++11)
    • explicit ( expression ) operator conversion-type-id (since C++20)

    Code [Compiler Explorer]:

    #include <iostream>
    
    class NewInt
    {
       int data;
    
    public:
    
       NewInt(int val=0)
       {
         data = val;
       }
    
       // Note that conversion-type-id "int" is the implied return type.
       // Returns by value so "const" is a better fit in this case.
       operator int() const
       {
         return data;
       }
    };
    
    int main()
    {
        NewInt A(10);
        std::cout << int(A);
        return 0;
    }