undefined behaviour ??

D

dragoncoder

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;
}
 
T

Thomas Tutone

dragoncoder said:
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
 
V

Victor Bazarov

dragoncoder said:
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
 

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,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top