#include <iostream>
usingnamespace std;
class B{
public:
int x;
B(int i=10) { x=i;cout<<"constr B("<<i<<")"<<endl;}
virtual B operator+(B ob) { B y(x+ob.x); cout<<"operator + from B"<<endl;return y;}
};
class D: public B{
public:
D(int i=10) { x=i;cout<<"constr D("<<i<<")"<<endl;}
voidoperator=(B p) { x=p.x; cout<<"operator = from D"<<endl;}
B operator+(B ob) { B y(x+ob.x+1); cout<<"operator + from D"<<endl; return y; }
void pr(){ cout<<x<<endl; }
};
int main(){
D p1(-59),p2(32),*p3=new D;
*p3=p1+p2;
p3->pr();
return 0;
}
Its output looks like that:
constr B(10)
constr D(-59)
constr B(10)
constr D(32)
constr B(10)
constr D(10)
constr B(-26)
operator + from D
operator = from D
-26
I don't understand why is "constr B(-26)" called (and also: why is it called before + operator)? ok, the lvalue needed to be type B, but in B there is no constructor with a type D parameter. shouldn't this type cast be illegal? I know that where B i s expected, it can be D. but i don't think it's correct the other way (to pass B where D is expected)