struct vs. class

Bill Baxter dnewsgroup at billbaxter.com
Tue May 29 19:57:45 PDT 2007


James Dennett wrote:
> Bill Baxter wrote:
>> Martin wrote:
>>> Gregor Richards Wrote:
>>>
>>>> Martin wrote:
>>>>> Inspired by the recent discussion about iterator structs/classes I
>>>>> wanted to ask - what's the design rationale behind having both
>>>>> structs and classes? In C++ the necessity was given by backwards
>>>>> compatibility but that doesn't apply to D of course. The only
>>>>> principal differences I can see (I'm not a D programmer (yet), so
>>>>> please correct me if I'm wrong) are a) that structs don't contain
>>>>> run-time meta information (a pointer to a vtable or however that
>>>>> works) and b) that struct variables are statically allocated as
>>>>> opposed to class variables which always seem to be pointers into
>>>>> dynamic memory.
>>>>> Somehow this looks really unorthogonal to me. Especially b) I find
>>>>> strange, can somebody explain the reason for this?
>>>>>
>>>>> cheers
>>>>> Martin
>>>> Firstly, your assertion about C++ is incorrect. C++ doesn't have
>>>> both, classes are just structs that are private by default, structs
>>>> are just classes that are public by default.
>>> Yes, I know that - still, formally they are two different things
>>> (albeit very similar).
>> And you can tell they're considered different things by the annoying
>> fact that if you forward declare a type with the wrong one, the C++
>> compiler will generate an error.
> 
> (No, but a non-C++ compiler might...)
> 
>> -----
>>    class Foobulator;
>>
>>    inline void function(Foobulator& fref) {
>>       . . .
>>    }
>> -----
>>    struct Foobulator {
>>       . . .
>>    };
>> -----
>> ==> Error Foobulator was declared as a class now it's a struct.
>>
>> grrr.  I don't care which it is Mr. silly compiler!  And you shouldn't
>> either!  All you need to know is that I can make a pointer to the darned
>> thing!
> 
> I know of only one compiler which fails to compile that, and
> it's a bug.  It's perfectly valid C++ code, and has been for
> a long, long time.

Hmm. Would that compiler be Microsoft Visual C++ 6.0?

> class Foobulator;
> 
> is *exactly* equivalent to
> 
> struct Foobulator;
> 
> in standard C++.  (Note the semi-colons on there, making
> these non-definitions.)


Hey, you're right!  I just tried it out in gcc.  Works fine.  And works 
for MSVC.NET 2003 too.  And DMC too!  Imagine that.

I'll go sit in a corner now.

--bb



More information about the Digitalmars-d mailing list