-2

I have the following structs

struct A 
{
   int i;
   A() { i = 0; }
   A(int _i) : i(_i) {}
   virtual void f() { cout << i; }
};



struct B1 : virtual A {
   B1() : A(1) { f(); }
   void f() { cout << i+10; }
};


struct B2 : virtual A {
   B2(int i) : A(2) { f(); }
};


struct C : B1, B2 {
   C() : B2(3) {}
};

please explain why the following code prints 100: (10+0)

 C* c = new C();

I think it should print 1111: first A() : i = 0 then B1() : i = 1 and prints B1::f() - 11 then B2() : prints prints B1::f() - 11

Where I go wrong?

Thanks

Aman Aggarwal
  • 3,905
  • 4
  • 26
  • 38
janneob
  • 959
  • 2
  • 11
  • 25
  • 1
    Adding some newlines to your print statements would help clarify the issue. – Oliver Charlesworth Feb 19 '12 at 12:46
  • -1 It's always worth doing a quick [google](http://www.google.co.uk/search?q=c%2B%2B+are+struct+members+public+or+private) first. The [wikipedia entry](http://en.wikipedia.org/wiki/C%2B%2B_classes#Differences_between_struct_and_classes_in_C.2B.2B) answers this one quite easily. – Samuel Harmer Feb 19 '12 at 12:49
  • -1, Bad descrption, does it print `10` or `100` now? Be more accurate and care more about how you ask your questions. – Niklas R Feb 19 '12 at 12:59
  • I have changed the question, please try to answer it now – janneob Feb 19 '12 at 13:10

3 Answers3

1

Public by default in a struct.

Robert S. Barnes
  • 39,711
  • 30
  • 131
  • 179
1

It doesn't print 100, it prints 10 followed by 0.

Struct means that the fields are private by default or public?

Public.

James M
  • 18,506
  • 3
  • 48
  • 56
  • I know for sure that it prints 10 and then 0 (this is the answer, but I can't understand why) Can you explain why? – janneob Feb 19 '12 at 12:47
1

Due to the inheritance, the C object "contains" a B1 object and a B2 object. Both the B1 and the B2 object "contain" an A object, but since you have virtual inheritance of A, you only have one A object in each C object, not two. This single A object is initialized using A's default constructor.

Thomas Padron-McCarthy
  • 27,232
  • 8
  • 51
  • 75