Conversion Operator : output of the following Program

#include
using namespace std;
 
class A {
 public:
    A(int ii = 0) : i(ii) {}
    void show() { cout << "i = " << i << endl;}
 private:
    int i;
};
 
class B {
 public:
    B(int xx) : x(xx) {}
    operator A() const { return A(x); }
 private:
    int x;
};
 
void g(A a)
{  a.show(); }
 
int main() {
  B b(10);
  g(b);
  g(20);
  getchar();
  return 0;
 
Output:
i = 10
i = 20
Since there is a Conversion constructor in class A, integer value can be assigned to objects of class A and function call g(20) works. Also, there is a conversion operator overloaded in class B, so we can call g() with objects of class B.

Comments

Popular Posts