Multiple Inheritance, C++ and Same Method Signature in Multiple Super Classes

后端 未结 5 1355
伪装坚强ぢ
伪装坚强ぢ 2021-01-31 18:42

I have no experience in C++, and I come from a Java background. Lately, I was asked in an interview on why Java would not allow multiple inheritence and the answer was pretty ea

5条回答
  •  抹茶落季
    2021-01-31 18:47

    struct MecEngineer {
    
         void buildRobot() { /* .... */ }
    
    };
    
    struct EleEngineer {
    
         void buildRobot() { /* .... */ }
    
    };
    
    struct RoboticsEngineer : MecEngineer, EleEngineer {
    
    };
    

    Now when you do,

    robEngObject -> buildRobot() ;
    

    Such a call cannot be resolved and is ambiguous because both the sub-objects has a member function with same signature and compiler doesn't know which one to call. In such a situation, you need to explicitly mention it using :: operator or by using static_cast.

    static_cast (robEngObject) -> buildRobot() ;
    

提交回复
热议问题