Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and Destructors in C#

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?

like image 905
user489041 Avatar asked Nov 17 '11 21:11

user489041


People also ask

What is destructor inheritance?

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).

What are destructors in C?

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() .

What is inheritance in C with example?

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.

Can destructor be inherited in C?

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.


1 Answers

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
like image 185
billpg Avatar answered Oct 31 '22 05:10

billpg