#include <stdio.h>
class InnerOne {
int m_iDummy;
public:
InnerOne(int iDummy) {
m_iDummy=iDummy;
}
InnerOne& operator=(InnerOne &obj) {
printf("In InnerOne Operator=\n");
m_iDummy = obj.m_iDummy;
return *this;
}
};
class OuterOne {
InnerOne m_innerOne;
public:
OuterOne(int iVal) : m_innerOne(iVal) {
}
};
int main() {
OuterOne a(1);
OuterOne b(2);
a = b;
return 1;
}
Will InnerOne ‘s operator = get called?
If yes then how and why?
Yes. The compiler generated copy-assignment for
OuterOnewill invoke theoperator=forInnerOne.As a sidenote, its better if you write
InnerOnecopy-assignment as:constis necessary, or else your code wouldn’t work for the following:See the error here : http://www.ideone.com/YMTJS
And once you add
constas I suggested, it’ll compile. See this : http://www.ideone.com/xj06z