Class member function calls inside ctor and dtor

Shachar Shemesh shachar at weka.io
Sun Jan 28 03:05:31 UTC 2018


On 28/01/18 03:13, Jonathan M Davis wrote:
> On Saturday, January 27, 2018 19:42:26 Steven Schveighoffer via Digitalmars-
> d wrote:
>> Well, a virtual function may expect that the ctor has been run, and
>> expect that members are different from their init values.
> 
> Yes, but you can have that problem even without getting inheritance involve.

Indeed. D's lack of proper definition of when underlying objects are 
initialized will strike you here as well.

However

Here, at least, you can view the problem locally. The problem is 100% 
contained in the constructor definition, and if it strikes you, you know 
where to look for it.

With the inherited class case, that's not so simple. I can inherit your 
class, and then you can change your class' destructor definition, and 
I'll be caught completely off guard.

A second point is that while the constructor may choose when to call the 
parent's constructor, the destructor has no such prerogative.

Finally, even if you can control when your parent is destroyed, that 
doesn't mean there is anything you can do about it. If your class 
inherently needs a functioning parent in order to do its stuff, then you 
have no choice but to call the parent's super before doing anything else 
in the constructor. If the parent then chooses to call virtual 
functions, you might be facing a problem with no tools to resolve it.

C++'s method of initializing parents is ugly as hell and a little 
confusing, but it is extremely clean and well defined. Both the compiler 
and the programmer know for sure what has been initialized, and no 
accidental calling of or relying on uninitialized members is possible.

Shachar


More information about the Digitalmars-d mailing list