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

Russell Lewis webmaster at villagersonline.com
Wed Dec 12 12:58:20 PST 2007


Gregor Richards wrote:
> BC wrote:
>> I thought it was a great idea to allow both value semantics
>> and pointer semantics for the same types in C++ by the simple
>> addition of a * or &. What was wrong with that that needed
>> to be fixed in D? GC could have been done without changing
>> this. Now in D template code doesn't know which
>> semantics apply and structs can't inherit. If you write
>> something as a struct and then realise you need inheritance
>> you're stuck. D has so many good ideas it's a shame to see
>> it broken in this way...
> 
> 
> No. No no no no no. I hate seeing this argument.
> 
> structs are a shim. They are a way of getting lower-level access to the 
> organization of memory.

In an abstract, academic sense, maybe you're right.  As a practical 
matter, they are (in D, at least) a way to organize your data without 
the runtime overhead of classes.  At least, that is one perfectly valid 
way to use them.

> In C++, this is ANYTHING but simple:
> 
> class A {
> ...
> }
> 
> void someidiotfunction(A a);
> void someidiotfunction2(A *a);
> void someidiotfunction3(A &a);
> 
> You now have three ways of passing an "object", with different semantics 
> and different possible results!
> 
> In proper object oriented design, objects are contexts. It makes no 
> sense to duplicate contexts. Contexts are an abstraction of an 
> environment in which to perform actions, and it makes no sense to 
> duplicate that environment whenever you happen to pass it from one 
> function to another (oh except when you don't).

I proposed a simple solution to this a while ago: disallow copying of 
classes, including passing them by value.  So, in your example above, I 
would propose that only the 2nd function should be valid, and the other 
2 should be syntax errors.  It's simple.  It's consistent with structs. 
  It enforces the "don't copy a context" paradigm you are talking about. 
  And it trivially teaches a newbie how to do things in D:

	Newbie: Write code that passes classes by value
	Compiler: Syntax Error!  You must pass classes by pointer
	Newbie: Hmm.  OK.  Can do.

Ofc, we'll get newbies on the newsgroup flaming us, asking why 
pass-class-by-value is disallowed, and we'll have to teach them.  But 
currently, what we have is a design that looks good at first (when 
writing trivial code) but which gets ugly when you write advanced code 
(like templates, or refactoring).



More information about the Digitalmars-d mailing list