Why isn't field-wise constructor automatic for structs and not classes?

rumbu via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jan 2 07:44:59 PST 2016


On Saturday, 2 January 2016 at 14:57:58 UTC, Shriramana Sharma 
wrote:
> John Colvin wrote:
>
>> Strictly speaking you aren't calling a constructor there, 
>> you're writing a struct literal.
>
> Why do you say I'm not calling a constructor?
>

A class constructor is written as:

auto s = *new* Timespan(1, 2);

> And that still doesn't answer the question of why can't we have 
> an automatic field-wise constructor for classes...

Probably because the inheritance:

class C1 { int x, y; }

class C2 : C1 { int z; }

How the C2 default memberwise constructor would look like? new 
C2(x, y)? or new C2(x, y, z)? What if x and y are private or 
reintroduced as public members in C2?

I think a default memberwise constructor for classes will break 
the encapsulation paradigm of OOP programming.


More information about the Digitalmars-d-learn mailing list