Answers for "operator int()"

C++
1

operator int()

// it's allow you to convert from an custom type in our case (number)
// to another data type like (int)
// without it ( operator int() ) the complier can not assign ob to x in this example below
class number{
float num;
public:
	number(float n=0)
    {
      num =n;
    }
  // operator that convert to int
  operator int()
  {
    return int(num)
  }
  
};// end of the class

int main()
{
  number ob(23.20);
  int x;
  x = ob;  // here we assign ob member to x
  
  return 0;
}
Posted by: Guest on July-28-2021

Browse Popular Code Answers by Language