I was going through notes about virtual destructors and virtual functions. Now, when I tried to write a simple code to validate my 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 I expect an output like so:
Constructing base
Constructing derived
inside void
Destructing base
because I didn't use the virtual keyword for the destructors of both derived and base? Can you please explain virtual functions and virtual destructors in view of this sample?
I get this 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 are getting the correct output.
Derived *d = new Derived();
d->doSomething();
It's calling the Derived class member function. For the runtime function call dispatch mechanism to work, you need to qualify the member functions with virtual
keyword. Also you should write -
Base *d = new Derived();
In the above case, static type of d
is different from the dynamic type. So, derived class member function will be called at runtime. Also, Base
class destructor should be virtual
in such scenario.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.