#include <iostream>
usingnamespace std;
//Why the op= is invoked twice
class A {
public:
A()
{
cout<<"A ctor"<<endl;
}
A(const A &a)
{
cout <<"A copy ctor"<<endl;
}
~A()
{
cout<<"A dtor"<<endl;
}
virtualvoid foo()
{
cout<<"A foo()"<<endl;
}
virtual A& operator=(const A &rhs)
{
cout<<"A op="<<endl;
}
};
class B:public A
{
public:
B():A()
{
cout<<"B ctor"<<endl;
}
~B()
{
cout<<"B dtor"<<endl;
}
virtualvoid foo()
{
cout <<"B foo()"<<endl;
}
protected:
A myIstanceOfA;
};
A foo (A &input)
{
input.foo();
return input;
}
int main()
{
B myB;
B myOtherB;
A myA;
myOtherB=myB;
myA=foo(myOtherB);
}
A ctor
A ctor
B ctor
A ctor
A ctor
B ctor
A ctor
A op=
A op= // WHY IS OP= EVOKED TWICE, IT SHOULD BE ONLY ONCE.
B foo()
A copy ctor
A op=
A dtor
A dtor
B dtor
A dtor
A dtor
B dtor
A dtor
A dtor
The op= or overloaded operator equal is evoked twice, where it should have only be once, any idea on what went wrong.
I remember seeing a program like this, but I think what's happening is that you're inheriting class A in your class B, so when you do it for class B it's gonna see everything that is pubilc in A, which in this case is everything. So it's inheriting the op part, which might cause it to print twice...
Note:
this is just a guess, so don't quote me on this, lol. I most likely am off in my reasoning.
Your B class inherits from your A class, which means in calls A's =. Since you also didn't define an = for B, the compiler will make one for you, which means it also calls the = on the A member in your B class.