Why structs and classes instanciations are made differently ?

Patrick Schluter via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 26 11:16:01 PDT 2017


On Monday, 24 July 2017 at 17:42:30 UTC, Steven Schveighoffer 
wrote:
> On 7/24/17 11:45 AM, Houdini wrote:
>> On Monday, 24 July 2017 at 15:41:33 UTC, Steven Schveighoffer 
>> wrote:
>> 
>>> Because types with inheritance generally don't work right if 
>>> you pass by value (i.e. the slicing problem).
>>>
>>> structs don't support inheritance or virtual functions, so 
>>> they can be safely passed by value.
>> 
>> But in C++, we pass them by reference also to avoid copies 
>> (const &).
>> The potential polymorphic usage is not the only point to 
>> consider.
>> 
>
> In C++ class and struct are pretty much interchangeable, so 
> technically, class is a wasted keyword for default visibility.
>
> In D, I would use classes for any time I need polymorphism, and 
> use structs otherwise.
>
> -Steve

It has also the nice property that porting code from Java/C# is 
actually really easy when using classes as it has more or less 
the same semantic. When porting code from C and C++ it is often 
better to use structs.



More information about the Digitalmars-d-learn mailing list