Virtual functions c++ -


i have tried exercises , when think understood, came exercise ruins everything. example have following classes:

class { public:     a() {std::cout<<"a()";}     virtual ~a(){std::cout<<"~a()";}       virtual void print() {std::cout<<"a";} };  class b : public { public:     b() {std::cout<<"b()";}     virtual ~b(){std::cout<<"~b()";}       virtual void print() {std::cout<<"b";} }; 

and following code snippets:

void f3() {     a[2];     a[1]=b();     a[1].print(); } 

and result think its:

a() a() a() b() {not sure why there a() too) - , here don't know because either , b virtual(and have in notebook a)  ~b() ~a() ~a() ~a() 

and code snippets:

void f4() {     a* a[]={new a(), new b()};     a[0]->print();     a[1]->print();     delete a[0];     delete a[1]; } 

and here problem too. have

a() {here don t know why there a()} a() b() b ~b() ~a() a() 

but it's correct? , why here have , b , not b , a?i mean, in first exercise have when type of b() , here it's how think it's normal why?

a() a() 

you created array of 2 a's, 2 calls of ctor.

a() b() {not sure why there a() too) 

you created b (b()), , bs derivated as, steps are: allocation of memory store b, call of a's ctor a-part, call of b's ctor b-part.

a - , here don't know because either , b virtual(and have in notebook a) 

you assigned fresh created b a, cause copy of a-part of b destination a. called print on a, , prints a.

~b() ~a() ~a() ~a() 

dtors called in exact reverse of ctors.

in second try, use pointers , dynamic allocations, , in case polymorphism used. array array of 2 pointers type a, initialized (the address of) 2 objects: first begin a, second b.

when call a[0]->print(), a[0] address of a, method print of called.

when call a[1]->print(), a[1] address of b, method print of called, because print virtual.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -