Why are structs and classes so different?

Kevin Bailey keraba at yahoo.com
Sun May 15 20:05:05 UTC 2022


Hi Mike (and Guillaume, since you posted the same link),

Thanks for the long explanation.

I've been programming in C++ full time for 32 years, so I'm 
familiar with slicing. It doesn't look to me like there's a 
concern here.

There seem to be a couple different questions here. I suspect 
that you answered a different one than I asked.

One question is, how should we pass objects - by value or by 
reference? In C++, you can do either, of course, but you take 
your chances if you pass by value - both in safety AND 
PERFORMANCE. The bottom line is that no one passes by value, even 
for PODs (although we may return even large objects.)

But I asked a different question: Why can't I put a class object 
on the stack? What's the danger?

Note that operating on that object hasn't changed. If I pass by 
reference, it's no different than if I had created a reference.

One might say, Well, if D creates by value, then it has to pass 
by value. But it doesn't; it has the 'ref' keyword.

One might want to avoid passing by value accidentally. Ok, one 
could have D pass class objects by reference implicitly.

I don't like things silently changing like that, so one might 
have D forbid all but pass by 'ref' or pointer for class objects.

In any case, this doesn't quite address the instantiate by value 
issue.

If there's still a case where putting an object on the stack 
breaks, I would greatly appreciate seeing a few lines of example 
code.

I hope Ali's answer isn't the real reason. I would be sad if D 
risked seg faults just to make class behavior "consistent".

thx



More information about the Digitalmars-d-learn mailing list