c++ - Strange (?) behavior with virtual keyword with g++ (Ubuntu) -


i going through notes virtual destructors , virtual functions. now, when tried write simple code validate learning,

#include <iostream> using namespace std;  class base{     public:     base (){         cout << "constructing base" <<endl;     }     void dosomething (){         cout << "inside void " << endl;     }     ~base (){         cout << "destructing base" << endl;     } }; class derived : public base{     public:     derived(){         cout << "constructing derived" << endl;     }     void dosomething (){         cout << "inside derived void " << endl;     }     ~derived(){         cout << "destructing derived" << endl;     } }; int main(){     derived *d = new derived();     d->dosomething();     delete d; } 

shouldn't expect output so:

constructing base constructing derived inside void destructing base 

because didn't use virtual keyword destructors of both derived , base? can please explain virtual functions , virtual destructors in view of sample?

i output:

constructing base constructing derived inside derived void  destructing derived destructing base 

i'm confused.

i use g++ (ubuntu/linaro 4.6.3-1ubuntu5) 4.6.3 in ubuntu 12.04.

you getting correct output.

derived *d = new derived(); d->dosomething(); 

it's calling derived class member function. runtime function call dispatch mechanism work, need qualify member functions virtual keyword. should write -

base *d = new derived(); 

in above case, static type of d different dynamic type. so, derived class member function called @ runtime. also, base class destructor should virtual in such scenario.


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -