A simple conversion function example. : conversion Function « Class « C++






A simple conversion function example.

A simple conversion function example.


#include <iostream>
using namespace std;

class MyClass {
  int x, y;
public:
  MyClass(int i, int j) { 
     x = i; 
     y = j; 
  }
  operator int() { 
     return x*y; 
  }
};

int main()
{
  MyClass object1(2, 3), object2(4, 3);
  int i;

  i = object1;                 // automatically convert to integer
  cout << i << '\n';

  i = 100 + object2;           // convert object2 to integer
  cout << i << '\n';

  return 0;
}



           
       








Related examples in the same category

1.Convert to char * in function callConvert to char * in function call