473,945 Members | 25,823 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

virtual function phenomenon

I found the following phenomenon in VC++ 2005:

struct A {};

struct B : public A
{
virtual ~B() {}
};

A* p = new B;
delete p; // crashes when executing this line

Does anyone have any insight into why it is crashing there?
Jul 22 '05 #1
4 1514

"Eric" <sh*****@yahoo. com> wrote in message
news:41******** @news.bezeqint. net...
I found the following phenomenon in VC++ 2005:

struct A {};

struct B : public A
{
virtual ~B() {}
};

A* p = new B;
delete p; // crashes when executing this line

Does anyone have any insight into why it is crashing there?


Because C++ says that this is undefined behaviour. If you delete a derived
class though a base class pointer then the base class *must* have a virtual
destructor.

Change to this and you will be OK.

struct A
{
virtual ~A() {}
};

struct B : public A
{
};

john
Jul 22 '05 #2

"John Harrison" <jo************ *@hotmail.com> wrote in message
news:30******** *****@uni-berlin.de...

"Eric" <sh*****@yahoo. com> wrote in message
news:41******** @news.bezeqint. net...
I found the following phenomenon in VC++ 2005:

struct A {};

struct B : public A
{
virtual ~B() {}
};

A* p = new B;
delete p; // crashes when executing this line

Does anyone have any insight into why it is crashing there?

Because C++ says that this is undefined behaviour. If you delete a derived
class though a base class pointer then the base class *must* have a

virtual destructor.


I had thought that what would happen is that the derived class destructor
would not be called but I see you're right about the standard saying the
behavior is undefined. If I make B::~B non-virtual then it runs ok and B::~B
is not called.. However making B::~B virtual causes it to crash.
Is there any simple explanation of this particular implementation mechanism
that causes it to crash when B::~B is made virtual?
Jul 22 '05 #3

"Eric" <sh*****@yahoo. com> wrote in message
news:41******** @news.bezeqint. net...

"John Harrison" <jo************ *@hotmail.com> wrote in message
news:30******** *****@uni-berlin.de...

"Eric" <sh*****@yahoo. com> wrote in message
news:41******** @news.bezeqint. net...
>I found the following phenomenon in VC++ 2005:
>
> struct A {};
>
> struct B : public A
> {
> virtual ~B() {}
> };
>
> A* p = new B;
> delete p; // crashes when executing this line
>
> Does anyone have any insight into why it is crashing there?
>


Because C++ says that this is undefined behaviour. If you delete a
derived
class though a base class pointer then the base class *must* have a

virtual
destructor.


I had thought that what would happen is that the derived class destructor
would not be called but I see you're right about the standard saying the
behavior is undefined. If I make B::~B non-virtual then it runs ok and
B::~B
is not called.. However making B::~B virtual causes it to crash.
Is there any simple explanation of this particular implementation
mechanism
that causes it to crash when B::~B is made virtual?


B contains a vtable, A does not. Therefore the A object embedded in the B
object is offset four bytes from the start of the whole object. Therefore
when you say delete p you are passing a pointer to the deallocation routine
that is different from the pointer that was allocated. At least that seems
to be what is happening on my platform. I bet if you add any virtual
function to A (not a destructor) it will no longer crash. Would still
technically be undefined behaviour of course.

Try this code, with and without the dummy function.

#include <iostream>
using namespace std;

class A
{
//virtual void dummy() {}
};

class B : public A
{
public:
virtual ~B() {}
};

int main()
{
B* b = new B();
A* a = b;
cout << "a = " << a << '\n';
cout << "b = " << b << '\n';
delete a;
}

john
Jul 22 '05 #4

"John Harrison" <jo************ *@hotmail.com> wrote in message
news:30******** *****@uni-berlin.de...

"Eric" <sh*****@yahoo. com> wrote in message
news:41******** @news.bezeqint. net...

"John Harrison" <jo************ *@hotmail.com> wrote in message
news:30******** *****@uni-berlin.de...

"Eric" <sh*****@yahoo. com> wrote in message
news:41******** @news.bezeqint. net...
>I found the following phenomenon in VC++ 2005:
>
> struct A {};
>
> struct B : public A
> {
> virtual ~B() {}
> };
>
> A* p = new B;
> delete p; // crashes when executing this line
>
> Does anyone have any insight into why it is crashing there?
>

Because C++ says that this is undefined behaviour. If you delete a
derived
class though a base class pointer then the base class *must* have a virtual
destructor.


I had thought that what would happen is that the derived class destructor would not be called but I see you're right about the standard saying the
behavior is undefined. If I make B::~B non-virtual then it runs ok and
B::~B
is not called.. However making B::~B virtual causes it to crash.
Is there any simple explanation of this particular implementation
mechanism
that causes it to crash when B::~B is made virtual?


B contains a vtable, A does not. Therefore the A object embedded in the B
object is offset four bytes from the start of the whole object. Therefore
when you say delete p you are passing a pointer to the deallocation

routine that is different from the pointer that was allocated. At least that seems
to be what is happening on my platform. I bet if you add any virtual
function to A (not a destructor) it will no longer crash. Would still
technically be undefined behaviour of course.


You're correct. I checked and the object layout is as follows:
VPTR < B*
A < A*
B

Adding a virtual function to A causes A to include the VPTR and then both A*
and B* point to the beginning of the object (the VPTR). This would seem to
be a logical implementation.

However, I tried it on the Borland compiler and there was no crashing and
the behavior was as I originally expected it would be.

It seems the Borland object layout with virtual B::~B is:
A < B* and A*
VPTR
B

and the Borland layout with virtual A::~A is:
VPTR < B* and A*
A
B
Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
12150
by: Roy Yao | last post by:
Hello, I need to pass a pointer to a callback function to the lower level modules. But the function is thought to be a virtual member one. How can I get the real address of the virtual member function?
23
2174
by: heted7 | last post by:
Hi, Most of the books on C++ say something like this: "A virtual destructor should be defined if the class contains at least one virtual member function." My question is: why is it only for the case when the class contains at least one virtual member function? Shouldn't the destructor always be virtual, whenever there's a possibility that an inherited object will be destructed through a base class pointer? (This does not require,
11
4406
by: santosh | last post by:
Hello, I was going through the Marshal Cline's C++ FAQ-Lite. I have a doubt regarding section 33.10. Here he is declaring a pure virtual destructor in the base class. And again defining it inline. Like this.
8
17796
by: Floogle | last post by:
how do i create a virtual == operator. I've tried the following but it's incorrect... class Interface { ... public: virtual bool operator==(const Interface& rhs)const=0;
6
3510
by: pakis | last post by:
I am having a problem of pure virtual function call in my project. Can anyone explaine me the causes of pure virtual function calls other than calling a virtual function in base class? Thanks
11
3485
by: ypjofficial | last post by:
Hello All, So far I have been reading that in case of a polymorphic class ( having at least one virtual function in it), the virtual function call get resolved at run time and during that the vtable pointer is made use of.. eg. class one {
10
4834
by: John Goche | last post by:
Hello, page 202 of Symbian OS Explained by Jo Stichbury states "All virtual functions, public, protected or private, should be exported" then page 203 states "In the rare cases where a pure virtual function body
7
2494
by: desktop | last post by:
This page: http://www.eptacom.net/pubblicazioni/pub_eng/mdisp.html start with the line: "Virtual functions allow polymorphism on a single argument". What does that exactly mean? I guess it has nothing to do with making multiple arguments in a declaration like:
17
3569
by: Jess | last post by:
Hello, If I have a class that has virtual but non-pure declarations, like class A{ virtual void f(); }; Then is A still an abstract class? Do I have to have "virtual void f() = 0;" instead? I think declaring a function as "=0" is the same
0
9974
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11548
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
11140
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11319
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10679
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7402
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4927
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3523
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.