3i Infotech Papers: Sample Questions 225 - 225 of 1245

Examrace Placement Series prepares you for the toughest placement exams to top companies.

Question number: 225

» Languages » C & C Plus Plus

Essay Question▾

Describe in Detail

Find the output of the following program

  1. class base
  2. {
  3.     public:
  4.     int bval;
  5.     base()
  6.     {
  7.         bval=0;
  8.     }
  9. };
  10. class deri:
  11. public base
  12. {
  13.     public:
  14.     int dval;
  15.     deri()
  16.     {
  17.         dval=1;
  18.     }
  19. };
  20. void SomeFunc(base *arrint size)
  21. {
  22.     for(int i=0i cout < bval;cout < < endl;)
  23. }
  24. int main()
  25. {
  26.     base BaseArr[5];
  27.     SomeFunc(BaseArr,5);
  28.     deri DeriArr[5];
  29.     SomeFunc(DeriArr,5);
  30. }

Explanation

  • 00000

    01010

  • In the program

Table showing the program

Table showing the program

  1. class base
  2. {
  3.     public:
  4.     int bval;
  5.     base()
  6.     {
  7.         bval=0;
  8.     }
  9. };
  • Define the base class

  • Define the integer variable bval

  • Here bval = 0

  1. class deri:
  2. public base
  3. {
  4.     public:
  5.     int dval;
  6.     deri()
  7.     {
  8.         dval=1;
  9.     }
  10. };
  • Define the deri class

  • Define the integer variable dval

  • Here dval = 1

  1. void SomeFunc(base *arrint size)
  2. {
  3.     for(int i=0i cout < 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) ).