mardi 21 juin 2022

type casting using constructors in C++

in the code below:

// implicit conversion of classes:
#include <iostream>
using namespace std;

class A {};

class B {
public:
  // conversion from A (constructor):
  B (const A& x) {}
  // conversion from A (assignment):
  B& operator= (const A& x) {return *this;}
  // conversion to A (type-cast operator)
  operator A() {return A();}
};

int main ()
{
  A foo;
  B bar = foo;    // calls constructor
  bar = foo;      // calls assignment
  foo = bar;      // calls type-cast operator
  return 0;
}

in the main function, foo is an object of type A. then in the next line when its written B bar = foo; what is converted to type B? after this line is the a an object of type B?

Aucun commentaire:

Enregistrer un commentaire