I have a Base class, that is considered read-only, and in it’s virtual desructor it does nothing.
Now I derive that Base class into a Derived class, which is writable, and in it’s destructor, it deletes the Base member:
class Base
{
virtual ~Base() {}
void* Data;
}
class Derive : public virtual Base
{
virtual ~Derive() { delete Data; }
}
Ignoring the syntactically incorrect code above, if I were to pass a Derive instance into a Function that takes the Base class as a reference:
void Function(const Base& base)
{
...
}
...
Derive der = Derive();
...
Function(der);
Would the Derived destructor be called at the end of the Function scope? I had trouble looking for the right keywords to find an answer, so my apologies if it’s been asked before. I am assuming the C++ treats references for what typw they are and not for type they could be, but I could be wrong.
No it wouldn’t, because the object doesn’t go out of scope. It goes out of scope, and is automatically destroyed after the call to
Function.If you were to pass the parameter by value instead of by reference:
the object would be sliced. The copy created inside
Functionis an object of typeBase(notDerive) so only theBasedestructor would be called when the function exits.