By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,305 Members | 1,843 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,305 IT Pros & Developers. It's quick & easy.

undefined behaviour ??

P: n/a
Consider the following code. Does it produce undefined behaviour
because destructor of A is not virtual ?

#include<iostream>
using namespace std;
class A
{
public:
A()
{
std::cout<<"In A's Constructor"<<std::endl;
}
~A()
{
std::cout<<"In A's Desstructor"<<std::endl;
}
};
class B:public A
{
public:
B()
{
std::cout<<"In B's Constructor"<<std::endl;
}
virtual ~B()
{
std::cout<<"In B's Desstructor"<<std::endl;
}
};
class C:public B
{
public:
C()
{
std::cout<<"In C's Constructor"<<std::endl;
}
~C()
{
std::cout<<"In C's Desstructor"<<std::endl;
}

};

int main()
{
A *b = new C();
delete b;
return 0;
}

Dec 20 '05 #1
Share this Question
Share on Google+
5 Replies


P: n/a
dragoncoder wrote:
Consider the following code. Does it produce undefined behaviour
because destructor of A is not virtual ?

#include<iostream>
using namespace std;
class A
{
~A()
{
std::cout<<"In A's Desstructor"<<std::endl;
}
};
class B:public A
{
virtual ~B()
{
std::cout<<"In B's Desstructor"<<std::endl;
}
};
class C:public B
{
public:
~C()
{
std::cout<<"In C's Desstructor"<<std::endl;
}

};

int main()
{
A *b = new C();
delete b;
return 0;
}


Yes, because you use a pointer to A.

Best regards,

Tom

Dec 20 '05 #2

P: n/a
Thomas Tutone wrote:
Yes, because you use a pointer to A.


Or, more accurately, because you delete a pointer to A.

Best regards,

Tom

Dec 20 '05 #3

P: n/a
dragoncoder wrote:
Consider the following code. Does it produce undefined behaviour
because destructor of A is not virtual ?
Yes.

[I've edited the code by snipping unnecessary functionality]
class A
{
public:
~A()
{
}
};
class B:public A
{
public:
virtual ~B()
{
}
};
class C:public B
{
public:
~C()
{
}
};

int main()
{
A *b = new C();
delete b;
return 0;
}


V
Dec 20 '05 #4

P: n/a
On 20 Dec 2005 06:44:04 -0800, "dragoncoder" <pk******@gmail.com>
wrote:
Consider the following code. Does it produce undefined behaviour
because destructor of A is not virtual ?


Yes.

--
Bob Hairgrove
No**********@Home.com
Dec 20 '05 #5

P: n/a
dragoncoder wrote:
Consider the following code. Does it produce undefined behaviour
because destructor of A is not virtual ?


Yes, exactly !

Have a look at :
http://www.codersource.net/cpp_virtual_destructors.html

Or type "virtual destructor c++" in google, and you will get an answer !

Regards,
Pierre-Andre Galmes
Dec 20 '05 #6

This discussion thread is closed

Replies have been disabled for this discussion.