Base object 1st, the inherited A object. The default ctor is used since we see no explicit call to it in the ctor, so inherited i=2
It's as if we have:
Now for deconstruction, stuff in the dtor body 1st:
~B() {
cout << i;// -> 2
--i;// now b.i=1
}
Next, the members of B (a1,a2,a3) are destroyed, in opposite the order declared:
For refc: ~A() { cout << i; }
~a3 -> 6
~a2 -> 5
~a1 -> 3
Lastly, the base A object is destroyed:
~B::A b.i -> 1
That's 26531
EDIT: Isn't the ninja effect amazing? No replies for 88 mins, then 2 in 5 mins.
class A{
protected:
int i;
public:
A(int n = 2) : i(n) {}
~A() { cout << i; }
};
class B : public A {
A a1;
A a2;
A a3;
public:
B(int n) : A(2), a1(i + 1), a2(n), a3(n+1) {}// just showing why b.i = 2
~B() {
cout << i;
--i;
}
};
int main(){
B b(5);
return 0;
}
output:
26531
Counterpoint!
anup30 wrote:
in output, 2 is from line19. 1 from line20.
The 1 is produced by line 9 when the base object is finally destroyed.
Line 20 accounts for why i=1 then.
@fun, you got what i meant. there is no point of confusion as line 20 is --i; there is no cout or printf in that line - any beginner can understand, it just says 1 is i's reduced value, reduced in line 20.(so printed from what line? i assumed that OP will figure out, or if he can't he will question.)