Hi.
I'm studing for the finals, and I came across this confusing code segment, to which I need to determine what will be the output:
I ran the code and this is the result I get:Code:class A { public: A(){cout<<"(1)"<<endl;} A(const A& s){cout<<"(2)"<<endl;} ~A(){cout<<"(3)"<<endl;} virtual void f1(){cout<<"(4)"<<endl;} virtual void f2(){cout<<"(5)"<<endl;} void f3(){cout<<"(6)"<<endl;} }; class B: public A { public: B(){cout<<"(7)"<<endl;} B(const B& a):A(a){cout<<"(8)"<<endl;} ~B(){cout<<"(9)"<<endl;} void f3(int i){cout<<"(10)"<<endl;} }; class C: public B { public: C(){cout<<"(11)"<<endl;} ~C(){cout<<"(12)"<<endl;} void f1(){cout<<"(13)"<<endl;} void f2(){cout<<"(14)"<<endl; B::f1();} }; int main() { A obj=B(); B* ptr1=new C(); ptr1->f2(); B* ptr2=new B(); ptr2->f2(); delete ptr1; delete ptr2; return 0; }
there are few thing that are'nt clear enough for me,Code:(1) (7) (2) //flag 1 (9) //flag 2 (3) //flag 2 (1) (7) (11) (14) (4) //flag 3 (1) (7) (5) //flag 4 (9) (3) (9) (3) (3) //flag 5
I flagged each one, and I would really appreciate some clarifications:
flag 1: why is A's C.Ctor called here, right after A and B Ctors?
flag 2: why are these destructors called? which object was destroyed here?
flag 3: how come A's f1() is called when clearly there is no f1() in B?
you might say that B inherits f1() from A, but B does not exist, there is no B object, only C exist here.
flag 4: ptr1 points to a C object, so how is it that C's destructor is not called here right after (5), but rather B's and A's? (is it because B's destructor isn't virtual?)
flag 5: that bothers me the most: where did that last (3) come from?
we have ptr2 pointing to a B object, which was just destroyed in line 42, therefor B's and A's destructors are called, but why is A's destructor called again?
any help would be greatly appreciated,
thanks in advance.