what was wrong with struct & class in C++?

Christopher Wright dhasenan at gmail.com
Sun Dec 16 08:54:41 PST 2007


Walter Bright wrote:
> Christopher Wright wrote:
>> That would be allowed in D, if you could overload T.opAssign(T).
> 
> C++ still has well-known slicing problems, even with overloading 
> assignment.

Yes, of course. You'd need to have a reference type behaving as a value 
type, with copy on assignment, in order to get rid of the issue. Though 
I'm not sure you're allowed to overload assignment from a reference or 
pointer to another reference or pointer in C++.

Besides which, people are going to use polymorphic types by value 
(actually by value, rather than some by-reference-and-by-value stuff) 
for performance reasons. Overload all you want, it won't help you when 
there's only 32 bytes for your struct on the stack and you need to pack 
in 48 bytes.

> The question is not "can this be done", it's more "is there a compelling 
> reason to support such behavior". I think the answer is no. Do you 
> really want a language where a class designer feels compelled to define 
> an opassign overload, then make it private to prevent people from using 
> the class as a value type? Where the base class designer needs to know 
> what the derived classes are doing so he can make the destructor virtual 
> or not? Where you cannot have arrays of base classes?

You'd need to create an opAssign overload in order to use a class as a 
value type, so you'd have to do zero work to prevent a class from being 
used as a value type. If you mean, create one and make it private in 
order for derived classes not to be used as value types, well, there'd 
better be a compelling reason for that. And making a private opAssign 
wouldn't help matters; I'd just make a new one on my derived class.

I'm not sure how arrays would be hindered by this.

Of course, if it's too much of an issue, you could define a construct 
'ref struct' that allows inheritance but has value semantics. If you 
think that programmers will have too much trouble with overloading 
assignment with classes. But that's introducing a new language construct 
rather than eliminating an exception to a rule.



More information about the Digitalmars-d mailing list