1

although we are printing bval, output is showing value of dval as well. Whats actual logic does compiler using? My expected output was 00000 00000, but I m getting output as 00000 01010.

#include <iostream>
using namespace std;

class base {
 public:
   int bval;
   base() { bval = 0; }
};

class deri : public base {
  public:
    int dval;
    deri() { dval = 1; }
 };

 void SomeFunc(base *arr , int size) {
   for(int i = 0; i < size; i++, arr++)
     cout << arr-> bval;
   cout<<endl;
 }

 int main() {
   base BaseArr[5];
   SomeFunc(BaseArr, 5);
   deri DeriArr[5];
   SomeFunc(DeriArr, 5);
   return 0;
 }
tehlexx
  • 2,821
  • 16
  • 29
nerdyator
  • 19
  • 2
  • 7

1 Answers1

3

You are cheating the system, and getting "slicing".

Since deri is larger than base, when you do arr++, the pointer is only advanced an base object forward.

The solution is to have an array of pointers, and passing a base **arr, like this:

base *foo[5];
base BaseArr[5];
SomeFunc(BaseArr,5);
for(int i = 0; i < 5; i++)
{ 
   foo[i] = &BaseArr[i];
}
SomeFunc(foo, 5);
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227