struct A
{
};
struct B: public A
{
B() {}
B( const A &rhs ){}
B & operator ++()
{
return ( *this );
}
};
const B operator ++( B &lhs, int )
{
++lhs;
return ( B() );
}
int _tmain(int argc, _TCHAR* argv[])
{
A a;
a++;
}
Why does the compiler issue the error
error C2678: binary '++' : no operator found which takes a left-hand operand
of type 'A' (or there is no acceptable conversion)
could be 'const B operator ++(B &,int)'
while trying to match the argument list '(A, int)'
Vladimir Grigoriev
You probably expect ::operator++(B(a), 0) to be called. However, a temporary can't bind to a non-const reference.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not necessarily a good idea. It is hard to be sure where they are going to land, and it could be dangerous sitting under them as they fly overhead. -- RFC 1925
So, it seems that the operator ++( T &, int ) is the only operator that does
not allow conversion from a base class to a derived class with using the
corresponding constructor.
Vladimir Grigoriev
"Igor Tandetnik" <itand...@mvps.org> wrote in message
news:u9uVhFyg...@TK2MSFTNGP06.phx.gbl...
I don't understand this claim. operator++ is a function like any other. If you had
void f(B&);
you wouldn't be able to call f(a) either (with language extensions disabled).
Vladimir Grigoriev
"Igor Tandetnik" <itand...@mvps.org> wrote in message
news:egqaPfyg...@TK2MSFTNGP02.phx.gbl...
The conversion produces a temporary. A temporary cannot be passed to a parameter of type reference-to-non-const. Your function takes just such a parameter. The fact that the function is called 'operator++' and not 'f' is irrelevant.
> With other operators which are written as a
> global function there is always a problem how to prevent using a base
> class object in a operator.
I suppose those other operators don't take non-const references as parameters.
Why do you want a constructor for a derived class from a base class in the first place? This doesn't seem to make much sense. Is it purely for academical interest, or are you trying to solve an actual problem this way?
Vladimir Grigoriev
"Igor Tandetnik" <itand...@mvps.org> wrote in message
news:%23Q9x$EzgKH...@TK2MSFTNGP04.phx.gbl...
Well, you could write it to take a const reference. Would make about as much sense as passing a temporary to it, but it would in fact compile.
You use increment mostly for the sake of its side effect on the operand. That's why it usually takes non-const reference - so it could modify its operand. That's also why it doesn't make sense to pass a temporary to it - it'll modify the temporary, which will soon die anyway, and the original object will remain unchanged.