Class member function calls inside ctor and dtor

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Jan 28 01:13:46 UTC 2018


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.
For instance,

class C
{
    immutable string s;

    this()
    {
        s = foo();
    }

    string foo()
    {
        return s ~ "foo";
    }
}

When foo is called from the constructor, s is null, whereas every time it's
accessed after that, it's "foo", meaning that the first time, foo returns
"foo" and all other times, it returns "foofoo". You can also do

class C
{
    immutable string s;

    this()
    {
        s = s ~ "foo";
    }
}

which surprised me. I thought that the compiler prevented you from using an
immutable variable before it was assigned in the constructor, but it
doesn't. It actually can't if you call any member functions unless it
required that all const and immutable members be initialized before calling
other functions, but it could at least prevent it within the constructor. It
doesn't though.

So, you can do some weird stuff with structs or classes that have been
initialized with their init values but not had all of their constructors
run, but because D initializes the object with the init value first, at
least you get something consistent out of the deal, and there are no
problems with the wrong version of a virtual function being called, because
the object was only partially constructed, whereas in C++, you can end up
crashing the program due to stuff like calling an abstract function that's
only defined in derived classes.

- Jonathan M Davis



More information about the Digitalmars-d mailing list