Suppose I have pointer of type ABC* and another pointer of type XYZ* and both derive from a common parent class.
If I assign XYZ* to ABC* by explicitly casting it, then what would happen if I call
delete abc; // abc is of type XYZ*
will I get any exception or will it work fine?
I have tried the above code and it doesn’t crashes. So can anyone tell me in what cases will delete throw exception/fault/crash etc?
What are the cases in which delet’ing a pointer crashes the program? Will they crash if both of them have custom destructors defined
Edit: Here is my test code which works without any crashes
class ABC
{
public:
int a;
int b;
int c;
};
class XYZ
{
public:
double a;
double b;
double c;
};
int main()
{
ABC* abc = new ABC();
XYZ* xyz = (XYZ*)abc;
delete xyz;
return 0;
}
P.S: I’m on Windows platform, if that helps.
EDIT2: Okay so after the readings, I change my question to, when will delete’ing a pointer cause a crash (not including the undefined behaviour)?
EDIT3: What will happen when delete is called? Whose destructor will be called?
If XYZ doesn’t derive from ABC then you shouldn’t be casting an object of the former to the latter – whether your delete works or not is immaterial.