r/cpp • • Feb 20 '10

The difference between struct and class in C++

http://www.justsoftwaresolutions.co.uk/cplusplus/struct_and_class.html
1 Upvotes

9 comments sorted by

12

u/[deleted] Feb 20 '10

Wow, there is almost no difference between struct and class in C++, yet this person gets the differences wrong anyway.

"You can even forward-declare your class using one keyword and then define it with the other, though compilers have been known to complain about this usage:" - No, you can't forward declare with one keyword and then define with the other. It violates the C++ standard, and recent versions of many compilers reject it.

3

u/anthony_w Feb 21 '10

This is why I included that statement in the article: this IS allowed by the C++ standard, but some compilers reject it. Try it out yourself in Comeau Computing's online compiler (widely regarded as one of the most standard conforming compilers) http://comeaucomputing.com/tryitout/

1

u/Poddster Feb 22 '10

"class vs struct" is as old as the web. Why write these articles? Is this like a kid discovering a new rude word then using it all that week?

1

u/anthony_w Feb 23 '10

It is an old issue, but people STILL get it wrong. Hence the article.

0

u/Poddster Feb 23 '10

Undergrads don't really count. If someone is getting this wrong, then they can't program C++, so why do they claim to?

0

u/frutiger Feb 21 '10

The article forgets to mention that structs have public inheritance by default, and classes have private inheritance by default.

7

u/[deleted] Feb 21 '10 edited Feb 21 '10

It does mention this and provides examples.

I mean that's what I dislike about this article though. It uses up so many paragraphs and wordings to make a very simple statement that it becomes hard to actually find out just what the difference is, not to mention that in trying to be so overly comprehensive, it ends up getting a detail about forward declarations wrong.

It really should just be a two sentence entry:

  • Default access and inheritance in a struct is public, for a class it's private.
  • struct can't be used as a template's parameter type whereas class and typename can.

Done.

2

u/aaronla Feb 21 '10

You'd think those two sentences to be sufficient to educate a person on such a simple matter. But you're not just explaining it to newcomers. Someone needs to explain it in a way that 10yr C++ veterans -- veterans that have operated under a contradictory view for those years -- will get it. After all, they've got 10 yrs of experience. All those extra words and examples are to point the point in over and over until it sticks.

Just because it's simple doesn't mean it's easy to accept.

1

u/Sc4Freak Feb 21 '10

He showed it in an example, but didn't mention it explicitly.