dimanche 28 février 2021

How does user defined conversion sequence work in C++ when initializing objects?

I have some question regarding user defined conversion sequence when performing copy initialization. let's say

#include <iostream>
struct Doodle {
  operator char() { return 'd' };
};

struct Penta {
  Penta(double) {};
  Penta()  = default;
};

int main() {
  Doodle d; 
  Penta p = 3.34; // works
  Penta another = d;

}

In last line it calls conversion function on d and calls Penta(double) constructor. What if I had a constructor that takes Doodle ? Will it call operator char() or Penta that takes Doodle constructor? I wish I could remember all those implicit conversion rules and sometimes these implicit conversions will be a headache in my opinion.

Aucun commentaire:

Enregistrer un commentaire