Non-binding of types



  • There are two classes:

    class A
    {
        public:
          A(int a_=0):x(a_) {}
          A operator + (A const &x_) const
          {
             return A(x+x_.x);
          }
          operator double() const
          {
             return (double) x;
          }
        private:
          int x;
    };
    class B
    {
        public:
          B(double b_=0):y(b_) {}
          B operator + (B const &y_) const
          {
             return B(y+y_.y);
          }
          operator int() const
          {
             return (int) y;
          }
        private:
          double y;
    };
    

    What will be the sequence of actions of the compiler in the following cases:

    A res_a(5);B res_b(10.5);
    A res_ab = res_a + res_b ; // <------
    A res_ba = res_b + res_a ; // <------
    B res_ab = res_a + res_b ; // <------
    B res_ba = res_b + res_a ; // <------
    


  • A little change in designers:

    B(double b_=0):y(b_) { cout << "B const" << y << endl; }
    A(int a_=0):x(a_) { cout << "A const" <<x << endl; }
    

    Let's start, and it's all clear:

    A res_ab = res_a + res_b ; // res_a->double, res_b->int, double->int, A(int)
    A res_ba = res_b + res_a ; // то же самое
    B res_ab = res_a + res_b ; // res_a->double, res_b->int, B(double)
    B res_ba = res_b + res_a ; // same
    

    In order to verify, we can get the type activation operators. In principle, this is understandable, as there is no A-B-condition, as is A+B.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2