c++ - simple ctor dilema - inheritance -


what outcome of following code, , please describe why :)

class mother {   public:     mother ( ) {         cout << "r" << endl;     }     ~mother ( )     {         cout << "n" << endl;     } }; class daughter: public mother {   public:     daughter ( )     {         cout << "a" << endl;     }     ~daughter ( )     {         cout << "b" << endl;     } }; void foo(mother m){ cout<< "foo" <<endl;} int main( ) {     daughter lea;     mother* rachel;     foo(lea); } 

i not sure why, told me be: r,a,foo,n,b,n (from left right)

why calling "daughter lea" generates r , a? due inheritance? , why did "foo" appear? shouldn't last? thanks!

this flow of program execution

int main( ) {     daughter lea;   // <- invokes ctor of daughter, after mother     mother* rachel; // nothing happens --pointer     foo(lea);       // foo->~mother, ~mother called upon exit }                   // ~daughter->~mother 

so, first, when creating lea, calls ctor of daughter. derived mother, mother ctor called first followed daughter, order of ctor calls in c++ base->derived

second line not pointer declaration.

now, here fun part, when call foo() lea, gets converted mother , passed foo. upon exit foo, ~mother called due local scope of mother in foo.

when program exits, destructs lea, of type daughter. order of destruction opposite order of construction. i.e derieved ->base, hence ~daughter followed ~mother.

that's why getting

r foo n b n 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -