the old virtual destructor nut

G

grahamo

Hi,

I recently did a test which required the user to note that a base
class had a non virtual destructor. Hence the dtor wouldn't be called
when the object was deleted.


The code is below (from memory) it's straightforward enough. My
question is this;

Does the spec say that the base classes dtor *wont* be called, or that
the behavior is undefined....The difference is subtle but all the same
its there. Am I correct in thinking that the behaviour is undefined?
According to Scott Meyers, it's undefined. I don't have a copy of the
spec but I'd like to get clarification.

thanks mulcho.

GrahamO


#include <iostream>

using namespace std;

class base
{
public:

base()
{
cout << "base()" << endl;
}

~base()
{
cout << "~base() " << endl;
}
};

class derived : public base
{
public:

derived()
{
cout << "derived()" << endl;
}

~derived()
{
cout << "~derived() " << endl;
}
};

derived* makeDerived()
{
return new derived();
};

base* makeBase()
{
return new base();
};

void cleanUp(base* b)
{
delete b;
}


int main(int argc, char** argv)
{

base* b = makeBase();
derived* d = makeDerived();

cleanUp(b);
cleanUp(d);


return 0;
}
 
M

Max M.

grahamo said:
The difference is subtle but all the same
its there. Am I correct in thinking that the behaviour is undefined?

You're correct. The difference is NOT subtle, though.
With my compiler, on my platform, the following code

class B1 { };
class B2 { }; // no virtual dtor!
class D: public B1, public B2 { };
int main()
{
D* dp = new D;
B2* b2p = dp;
delete b2p;
}

causes a segmentation fault.
(Note that multiple inheritance is involved.)

Max
 
G

grahamo

Thanks a million for that Max. All I have to do now is let the guy
that interviewed me know that his test is wrong.. ! :) :) Better wait
until I actually get the job though:)


cheers mate

GrahamO
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top