According to this, it states that Destructors cannot be inherited or overloaded.
In my case, for all subclasses, the destructors will be identical. Is this pretty much telling me that I must define the same destructor in each sub class. There is no way that I can declare the destructor in the base class and have the handle the destruction? Say I have something like this:
class A
{
~A()
{
SomethingA();
}
}
class B : A
{
}
B b = new B();
When B
is destroyed, its destructor wont be called?
Destructors are not inherited. If a class doesn't define one, the compiler generates one. For trivial cases that destructor just calls the base class' destructor, and often that means that there is no explicit code for its destructor (which imitates inheritance).
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ). For example, the destructor for class String is declared: ~String() .
In C, inheritance can be achieved by maintaining a reference to the base class object in the derived class object. With the help of the base class' instance, we can access the base data members and functions.
Destructors and InheritanceBecause the base class destructor is inherited, and because the derived class object "is" a base class object, both the derived class destructor (even if it is the "default" destructor) and the base class destructor are called automatically.
A quick console app can help test this sort of thing.
using System;
class A
{
~A() => Console.WriteLine("~A");
}
class B : A
{
~B() => Console.WriteLine("~B");
}
public class Program
{
public static void Main() => new B();
}
The output might be...
~B
~A
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