-2

Here the data member of the base class is private. Please explain this code. why the output of this program is 80.

  #include<iostream> 
  using namespace std; 

  class base { 
      int arr[10]; 
   }; 
      
  class b1: public base { }; 
      
  class b2: public base { }; 
      
  class derived: public b1, public b2 {}; 
      
  int main(void) 
  { 
    cout << sizeof(derived); 
    return 0; 
  } 
Botje
  • 26,269
  • 3
  • 31
  • 41
Jeel Patel
  • 43
  • 6
  • 5
    This is the diamond problem, see [How does virtual inheritance solve the "diamond" (multiple inheritance) ambiguity?](https://stackoverflow.com/questions/2659116/how-does-virtual-inheritance-solve-the-diamond-multiple-inheritance-ambiguit) – Botje Aug 31 '20 at 11:29
  • 1
    Are you expecting a private member to occupy less space than other members? – molbdnilo Aug 31 '20 at 11:35
  • @Botje There is no diamond here. `derived` just has two subobjects of `base` type – user7860670 Aug 31 '20 at 11:35
  • what output did you expect? Why do you think `80` would be a problem? – 463035818_is_not_an_ai Aug 31 '20 at 11:39
  • 2
    @user7860670 The inheritance diagram looks like a diamond and OP has the exact problem listed in [the C++ faq](https://isocpp.org/wiki/faq/multiple-inheritance#mi-diamond) – Botje Aug 31 '20 at 11:40
  • Please formulate your question better; now people are guessing and make fun of it. 'Botje' already explained why the size is 80 and not 40 if that's what you had expected. – gast128 Aug 31 '20 at 11:50

1 Answers1

0

You misunderstand what private modifier does. In your code snippet it simply prevents non-members and non-friends of A from accessing it. It's just an access-control modifier. Instances of child class will have data members of its parent, even though child class won't have (direct) access to it.

NOTE : if private, child class cannot peek in parent even though it contains it.