[Issue 5056] Warning against virtual method call from constructor

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Oct 15 09:48:36 PDT 2010


http://d.puremagic.com/issues/show_bug.cgi?id=5056


Jonathan M Davis <jmdavisProg at gmx.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |jmdavisProg at gmx.com


--- Comment #1 from Jonathan M Davis <jmdavisProg at gmx.com> 2010-10-15 09:47:59 PDT ---
It should be noted that unlike C++ this isn't necessarily a problem in D. In
C++, each class in the class's hierarchy is constructed one by one until the
most derived class constructor is called. So, if you call a virtual function in
a constructor, the object is not in a safe state and won't even correctly know
what type it is.

In D, however, the object is in a safe state. All of the classes in its
hierarchy are properly put together with the default values for all their
variables already initialiazed, _then_ the constructors are called. So, virtual
functions will work correctly. It is perfectly safe to call them.

Now, it's quite possible that you write your class poorly and a virtual
function that you call in your constructor assumes that the super classes'
constructors have already been called, and it doesn't do what you expect, but
it's nowhere near the same problem as it is in C++. And since, unlike C++,
nearly all member functions in D are virtual, you have somewhat less control
over whether a function is or isn't virtual, and it will be that much harder to
guarantee that a function isn't virtual. You'd be restricted to private
functions and public final functions which don't override base class functions.
In many cases, that is unnecessarily restrictive.

So, while this is definitely a concern in C++, I'm not sure that there's much
pont in worrying about it in D. D has specifically been designed to avoid the
worst problems associated with calling virtual functions in a constructor.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list