3i Infotech Placement: Sample Questions 230 - 230 of 1245

Glide to success with Doorsteptutor material for competitive exams : get questions, notes, tests, video lectures and more- for all subjects of your exam.

Question 230

Edit

Describe in Detail

Essay▾

Find the output of the following program

  1. classbase
  2. {
  3.     public:
  4.     intbval;
  5.     base()
  6.     {
  7.         bval=0;
  8.     }
  9. };
  10. classderi:
  11. publicbase
  12. {
  13.     public:
  14.     intdval;
  15.     deri()
  16.     {
  17.         dval=1;
  18.     }
  19. };
  20. voidSomeFunc(base ⚹arr, intsize)
  21. {
  22.     for(inti=0; icout <bval;cout << endl;)
  23. }
  24. intmain()
  25. {
  26.     baseBaseArr[5];
  27.     SomeFunc(BaseArr,5);
  28.     deriDeriArr[5];
  29.     SomeFunc(DeriArr,5);
  30. }

Explanation

  • 00000

    01010

  • In the program
Table Showing the Program
  1. classbase
  2. {
  3.     public:
  4.     intbval;
  5.     base()
  6.     {
  7.         bval=0;
  8.     }
  9. };
  • Define the base class
  • Define the integer variable bval
  • Here bval = 0
  1. classderi:
  2. publicbase
  3. {
  4.     public:
  5.     intdval;
  6.     deri()
  7.     {
  8.         dval=1;
  9.     }
  10. };
  • Define the deri class
  • Define the integer variable dval
  • Here dval = 1
  1. voidSomeFunc(base ⚹arr, intsize)
  2. {
  3.     for(inti=0; icout <bval;cout ≪ endl;)
  4. }
  • The function SomeFunc expects two arguments.
  • The first one is a pointer to an array of base class objects and the second one is the sizeof the array.
  • The first call of someFunc calls it with an array of base objects, so it works correctly and prints the bval of all the objects.
  • When Somefunc is called the second time the argument passed is the pointer to an array of derived class objects and not the array of base class objects.
  • But that is what the function expects to be sent. So the derived class pointer is promoted to base class pointer and the address is sent to the function.
  • SomeFunc () knows nothing about this and just treats the pointer as an array of base class objects.
  • So when arr ++ is met, the size of base class object is taken into consideration and is incremented by sizeof (int) bytes for bval (the deri class objects have bval and dval as members and so is of size >= sizeof (int) + sizeof (int) ) .

Developed by: