Pergunta de entrevista da empresa Capgemini

I was asked to write a code in C++ for a simple integer class that stores two variables, object1 and object2, and adds them into a third variable, object3.

Resposta da entrevista

Sigiloso

23 de fev. de 2025

Here was my initial code: cpp class obj1 { public int val = 1; return val; } class obj2 : obj1 { public int val1 = 2; return val1; } class virtual obj3 : obj2, obj1 { public int val3; val3 = obj1.val + obj2.val1; return val3; } I realized my approach was incorrect as I used inheritance instead of a single Integer class. My code had several issues, including incorrect class declarations, inappropriate use of return statements, and improper inheritance syntax. Here’s an improved version: cpp #include class Object1 { public: int val; Object1() : val(1) {} // Constructor to initialize val }; class Object2 { public: int val1; Object2() : val1(2) {} // Constructor to initialize val1 }; class Object3 { public: int val3; Object1 obj1; Object2 obj2; Object3() { val3 = obj1.val + obj2.val1; // Adding values from obj1 and obj2 } int getVal3() const { return val3; } }; int main() { Object3 obj3; std::cout << "Value of val3: " << obj3.getVal3() << std::endl; return 0; } However, the correct approach should have been a single Integer class: cpp #include class Integer { private: int object1; int object2; public: Integer(int obj1, int obj2) : object1(obj1), object2(obj2) {} int add() { return object1 + object2; } }; int main() { Integer obj(5, 10); int object3 = obj.add(); std::cout << "The result of adding object1 and object2 is: " << object3 << std::endl; return 0; } I learned a lot from this experience and appreciate the opportunity to improve my skills.