I was playing around with some of c++ futures, and got into something that does intrigue me.
class Base
{
public:
Base(){ cout<<"C: Base"<<endl;}
~Base(){ cout<<"D : Base"<<endl;}
};
class Derived: public Base
{
public:
Derived(){ cout<<"C: Derived"<<endl;}
~Derived(){ cout<<"D : Derived"<<endl;}
};
class Derived2: public Derived
{
public:
Derived2(){ cout<<"C: Derived2"<<endl;}
~Derived2(){ cout<<"D : Derived2"<<endl;}
};
class Derived3: public Derived2
{
public:
Derived3(){ cout<<"C: Derived3"<<endl;}
~Derived3(){ cout<<"D : Derived3"<<endl;}
};
void main()
{
Derived *Var = new Derived2();
delete (Derived3*)Var; //<---- this should cause some type of run-time error
}
Why does the above not generate an error. Is it because there is not data in Derived3 to release. Or am I missing something?
But instead it outputs
C: Base
C: Derived
C: Derived2
D : Derived3 <--- SHOULD NOT BE POSSIBLE
D : Derived2
D : Derived
D : Base
C++ language doesn't have any extensive system of "run-time errors". Some language features can throw exceptions or call terminate(), which are "run-time errors" indeed, but invalid delete is not one of these features.
Doing something as invalid as what you are dong is causing undefined behavior in C++. Undefined behavior means that anything can happen, anything is possible. Your program might even behave as if it is "working" in some way. This is what you observe.
Experimenting with undefined behavior is a pointless exercise. The results you observe mean absolutely nothing and are generally not repeatable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With