Reputation: 175
I'm kind of confused about how the reference works in the code below.
From what I understand, b is just an alias of d1. So what's the difference between delete &b
and delete d1
?
b is of type Base but still is an alias of type f, so what differentiates them?
#include <iostream>
using namespace std;
class Base
{
public:
Base(){
cout << "Base Constructor Called\n";
}
~Base(){
cout << "Base Destructor called\n";
}
};
class Derived1: public Base
{
public:
Derived1(){
cout << "Derived constructor called\n";
}
~Derived1(){
cout << "Derived destructor called\n";
}
};
int main()
{
Derived1 *d1 = new Derived1();
Base &b = *d1;
delete &b;
}
Upvotes: 0
Views: 64
Reputation: 385385
They are differentiated by type.
b
refers to an object of type Base
.
d1
points to an object of type Derived1
.
Those are related, but distinct types.
Your object is a Derived1
, not just a Base
. This matters to delete
. Make your destructors virtual and you'll get away with it, because that's how polymorphism works. Otherwise, you have undefined behaviour and there is no meaning to your program.
Upvotes: 2