D classes inherane. How it works.

Gregor Richards Richards at codu.org
Tue Apr 8 10:31:51 PDT 2008


Every destructor in the hierarchy will be called. I don't recall if you 
can do something like ~super(), but the default is exactly as you see: 
bottommost destructor to topmost destructor. flush() in A is being 
called because ~this() in A calls it.

So, you have to make sure that B's destructor doesn't destroy any data 
that is in fact owned by its parent class, A. Why would you, though?

However, as Janice mentioned, destructors aren't really that useful in a 
GC'd language. They're only useful when your class is stapling itself to 
some lower-level resource, like malloc'd memory or fopen'd files. I 
don't think I've actually written a destructor in any D code. At all.

  - Gregor Richards


Jason House wrote:
> D uses virtual functions by default (and C++ does not).  Most of your code is showing virtual function handling vs. non-virtual function handling.
> 
> I'm unclear on how flush is getting called at all.
> 
> kov_serg Wrote:
> 
>> Sorry, for silly question by could anyone give link where I could found how D constructor and destructors works. The behavious is very nice but much different from C++. 
>>
>> import std.stdio;
>>
>> class A {
>> 	void init()  { writefln("A.init"); }
>> 	void fn()    { writefln("A.fn"); }
>> 	void flush() { writefln("A.flush"); }
>> 	this()       { writefln("A");init(); }
>> 	~this()      { flush();writefln("~A"); }
>> }
>>
>> class B : A {
>> 	void init()  { writefln("B.init"); }
>> 	void fn()    { writefln("B.fn"); }
>> 	void flush() { writefln("B.flush"); }
>> 	this() { writefln("B"); }
>> 	~this() { writefln("~B"); }
>> }
>>
>> void main() {
>> 	writefln("D1.0 main");
>> 	A a=new B;
>> 	a.fn();
>> 	delete a;
>> }
>> /*
>>
>> D1.0 main
>> 	A
>> 	B.init
>> 	B
>> 	B.fn
>> 	~B
>> 	B.flush
>> 	~A
>>
>> C++ version
>> 	A
>> 	A.init (no B vft yet)
>> 	B
>> 	B.fn
>> 	A.flush (dtor overrides vft)
>> 	~A
>>
>> */
>>
>> ps: C++ version more strong but hardly usefull. D version looks much better for me. But how it implemented or should be implemented. If ~B already kills his resources?
> 



More information about the Digitalmars-d mailing list