Topic: which class function to call in presence of type conversions


Author: sbnaran@bardeen.ceg.uiuc.edu (Siemel Naran)
Date: 1998/06/29
Raw View
Summary: We have a base class B and two derived classes D1 and D2.
D1 may define an operator= that takes a B as its argument.  When we
say "d1=d2", what exactly happens?

Run the program as is, with "D1::operator=(const B&)" defined.  What
should the last line of output be?
   (1) "d1=12 1"
   (2) "d1=12 20"
In other words, should the program do
   (1) d1.operator=((B&)d2)
   (2) d1.operator=(D1(d2))
g++ tells me (1).  Which makes sense because the conversion D1==>B
is simpler than the conversion D1==>D2.  Note that the results
should be the same even if the prototype were "D1::operator=(B)".


Now run the program without "D1::operator=(const B&)" defined, which
is better style, IMHO, given the type conversions.  What's the output?
   (1) "d1=12 1"
   (2) "d1=12 20"
g++ tells me (2).








#include <iomanip.h>

struct B
{
     int b;
     static int bs;

     B() : b(bs++) { }
};

int B::bs=11;

struct D1;
struct D2;

struct D1 : public B
{
     int d;

     D1() : d(1) { }
     D1(const D2&);

     D1& operator=(const B& that) { b=that.b; return *this; }
};

struct D2 : public B
{
     int d;

     D2() : d(2) { }
     D2(const D1&);
};

D1::D1(const D2& that) : B(that), d(that.d*10) { }
D2::D2(const D1& that) : B(that), d(that.d   ) { }



inline ostream& operator<<(ostream& strm, const D1& d1)
{
     return strm << d1.b << ' ' << d1.d;
}

inline ostream& operator<<(ostream& strm, const D2& d1)
{
     return strm << d1.b << ' ' << d1.d;
}

int main()
{
     D1 d1; // d1.b=11, d1.d=1
     D2 d2; // d2.b=12, d2.d=2

     cout << "d1=" << d1 << endl;

     cout << "d1=d2" << endl;
     d1=d2;
        /* if D1::operator=(const D1&) called ==> d1.b=12, d1.d=20
           if B ::operator=(const B &) called ==> d1.b=12, d1.d=1
        */

     cout << "d1=" << d1 << endl;
}




--
----------------------------------
Siemel B. Naran (sbnaran@uiuc.edu)
----------------------------------
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]