6

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.

Matthias
  • 4,481
  • 12
  • 45
  • 84
darkstylazz
  • 63
  • 1
  • 1
  • 4

1 Answers1

8

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;
} 
Matthias
  • 4,481
  • 12
  • 45
  • 84
  • Thank you very much! If I changed int for float in the definition, would it automatically cast it to float? – darkstylazz Feb 22 '20 at 22:32
  • @darkstylazz It would support implicit casts to `float` in that case. Whether such a cast would actually happen depends on the use case of course. – Matthias Feb 23 '20 at 14:04