3
$\begingroup$

C++ notably has a way to skip initialization of members:

struct A {
    A(){ std::cout<<"A()"<<std::endl; }
    A(int x){ std::cout<<"A(int)"<<std::endl; }
    A(bool x){ std::cout<<"A(bool)"<<std::endl; }
};

struct B {
    A x;
    A y{true};
    A z = (std::cout<<"B.z"<<std::endl, A(false));
    B() : x(1), y(2), z(3) {}
}; // Only calls A(int) three times

Try it online!

But it's cumbersome to use. You loses most of the features of modern programming while writing initialization.

Java has super() to call the constructor of the parent class between the lines. But as I'm aware of, it doesn't provide a way to skip previously defined initializations for general members. Variables with complex constructors could all be defined to be nulls, without calling a constructor, so it's not a big problem in Java.

If I want the feature to skip the previously defined initialization like in C++, or at least to skip the implied initialization at definition, but also make it appear like a general expression or statement, like in Java, is there a good way to design the syntax? Say, are there existing languages doing this?

I'm asking because I feel doing this arbitrarily will make it prone to human errors.

This is very similar to the distinction of shadowing and overriding virtual functions. So I suppose they could use the same syntax. Languages tends to use two keywords to make the distinction for virtual functions. But the feature in question has three instead of two semantics to be differentiated, that is to shadow, ignore previous actions, and assign. Mistakes are less diagnosable. And shorter syntaxes are expected because assignments are very frequently used.

$\endgroup$

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.