简体   繁体   中英

Does C++ calls member object 's overloaded operator?

 #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 automatically generated assignment operator for OuterOne will call the assignment operator of InnerOne .

Yes. The compiler generated copy-assignment for OuterOne will invoke the operator= for InnerOne .

As a sidenote, its better if you write InnerOne copy-assignment as:

InnerOne& operator=(const InnerOne &obj)
                  //^^^^ add this!

const is necessary, or else your code wouldn't work for the following:

const InnerOne x(10);
InnerOne y(10);

y = x; //compilation error - if you use your code

See the error here: http://www.ideone.com/YMTJS

And once you add const as I suggested, it'll compile. See this: http://www.ideone.com/xj06z

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM