HackerRank C++ Accessing Inherited Functions




You are given three classes A, B and C. All three classes implement their own version of func.

In class A, func multiplies the value passed as a parameter by 2:
In class B, func multiplies the value passed as a parameter by 3:
In class C, func multiplies the value passed as a parameter by 5:
You are given a class D
You need to modify the class D and implement the function update_val which sets D's val to new_val by manipulating the value by only calling the func defined in classes A, B and C.



  1. #include<iostream>
  2. using namespace std;
  3. int callA=0;
  4. int callB=0;
  5. int callC=0;
  6. class A
  7. {
  8. protected:
  9. void func(int & a)
  10. {
  11. a=a*2;
  12. callA++;
  13. }
  14. };
  15. class B
  16. {
  17. protected:
  18. void func(int & a)
  19. {
  20. a=a*3;
  21. callB++;
  22. }
  23. };
  24. class C
  25. {
  26. protected:
  27. void func(int & a)
  28. {
  29. a=a*5;
  30. callC++;
  31. }
  32. };
  33. class D : public A,public B,public C
  34. {
  35. int val;
  36. public:
  37. //Initially val is 1
  38. D()
  39. {
  40. val=1;
  41. }
  42. //Implement this function
  43. void update_val(int new_val)
  44. {
  45. int a = new_val;
  46. while ( a %2 == 0)
  47. {
  48. a = a/2;
  49. A::func(val);
  50. }
  51. while ( a % 3 == 0)
  52. {
  53. a = a/3;
  54. B::func(val);
  55. }
  56. while ( a % 5 == 0)
  57. {
  58. a = a/5;
  59. C::func(val);
  60. }
  61. }
  62. //For Checking Purpose
  63. void check(int); //Do not delete this line.
  64. };
  65. void D::check(int new_val)
  66. {
  67. update_val(new_val);
  68. cout<<"Value = "<<val<<endl<<"A's func called "<<callA<<" times "<<endl<<"B's func called "<<callB<<" times "<<endl<<"C's func called "<<callC<<" times"<<endl;
  69. }
  70. int main()
  71. {
  72. D d;
  73. int new_val;
  74. cin>>new_val;
  75. d.check(new_val);
  76. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube