A
Alexander Stippler
Given the following code snippet we get some unexpected behaviour:
//--------------------------------------------------------------------
#include <iostream>
using namespace std;
struct A
{
A() { cerr << "A()" << endl; }
};
struct C;
struct B : public A
{
B();
explicit
B(const B &rhs);
B(const A&rhs);
C
operator()(int from, int to);
};
struct C: public A
{
B r;
operator const B &() const;
};
B::B() { cerr << "B()" << endl; }
B::B(const B &rhs)
{ cerr << "B(const B &rhs)" << endl; }
B::B(const A &rhs)
{ cerr << "B(const A &rhs)" << endl; }
C
B:perator()(int from, int to) { return C(); }
C:perator const B &() const
{ cerr << "operator const B &() const" << endl;
return r;
}
int main()
{
C c;
B b = c; // conversion constructor called twice here - why??
return 0;
}
//--------------------------------------------------------------------
The conversion constructor B(const A &) is called twice when
initializing object b. We would expect a call of
C:perator const B &() const
and then one call of
B::B(const B &).
//--------------------------------------------------------------------
#include <iostream>
using namespace std;
struct A
{
A() { cerr << "A()" << endl; }
};
struct C;
struct B : public A
{
B();
explicit
B(const B &rhs);
B(const A&rhs);
C
operator()(int from, int to);
};
struct C: public A
{
B r;
operator const B &() const;
};
B::B() { cerr << "B()" << endl; }
B::B(const B &rhs)
{ cerr << "B(const B &rhs)" << endl; }
B::B(const A &rhs)
{ cerr << "B(const A &rhs)" << endl; }
C
B:perator()(int from, int to) { return C(); }
C:perator const B &() const
{ cerr << "operator const B &() const" << endl;
return r;
}
int main()
{
C c;
B b = c; // conversion constructor called twice here - why??
return 0;
}
//--------------------------------------------------------------------
The conversion constructor B(const A &) is called twice when
initializing object b. We would expect a call of
C:perator const B &() const
and then one call of
B::B(const B &).