7

struct is public by default while class is private by default.

Lets take Ogre3D for example; if I change all class occurences with struct, it compiles (I guess), and the engine works just as before.

If I'm right, the compiled code is exactly the same as before, because it's only the compiler that does check if a private/protected methods are called, it's not checked at runtime.

If I'm still right, class is just a keyword that just makes its cute eyes and begging "please encapsulate your data: you'll save a kitten", while private/protected scopes are still up to the user.

I know I sound kinda lame or irrelevantly rebel (something like "C is KISS dude, don't go "

Back to the question: what does the standard say about this little difference between struct and class while generating machine code ? Why add a keyword and try to impress programmers with the so called "OO model" while it's totally not enforced then ? Was it influenced by java ?

jokoon
  • 6,207
  • 11
  • 48
  • 85
  • 7
    Quite the opposite actually. You kill a kitten every time you use the 'class' keyword where 'struct' would suffice. No, wasn't influenced by Java since C++ came first. – Edward Strange Jan 24 '11 at 17:28
  • 2
    C++ is not a strictly OO language, it's a multi-paradigm language that supports more than just OO, so it doesn't seek to enforce OO concepts on the developer. It's up the the developer to use OO style if they wish to. See the C++ tag's info entry here http://stackoverflow.com/tags/c%2b%2b/info – Glen Jan 24 '11 at 17:28
  • There are more answers to this question at http://stackoverflow.com/questions/4090794/c-when-should-i-use-structs-instead-of-classes-and-where-are-the-speed-differe . – Jeremiah Willcock Jan 24 '11 at 17:30
  • 2
    "Why add a keyword" - because in C++ it *should* be `class`, but `struct` is there too for backward compatibility to C. Don't worry, nobody is trying to impress you. Actually it might have been useful for the compiler to enforce that any class defined with `struct` must be POD, but no such luck. – Steve Jessop Jan 24 '11 at 18:26
  • 1
    "Was it influenced by Java?" ha ha ha. That's funny! – John Dibling Jan 25 '11 at 14:14

10 Answers10

5

The standard says nothing about generating machine code at all.

struct was retained to make migrating legacy C code easier. Typically, C++ programmers use it for POD-like structures.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 1
    Correct. Only I tend to use `struct` almost always. I only use `class` if I have `private` or `protected` members and no public members other than the compiler-generated or inherited members. This because I like placing my private members at the bottom, because they're the least interesting in a class' interface. – wilhelmtell Jan 24 '11 at 18:28
4

Actually, class and struct are both checked at compile time. The only difference is whether the default for members who you've not explicitly specified the access for are public (for a struct) or private (for a class). Otherwise, they produce exactly the same objects. If you specify all of your access control explicitly, you can use either one and they will be the same.

Jeremiah Willcock
  • 30,161
  • 7
  • 76
  • 78
  • There is no guarantee that they do generate the same code. In particular the layout of the data members of a class is guaranteed to have increasing memory addresses only within the same block. A class with all public members or all private members will have the same layout, but a conforming compiler could decide to place all public members (in order) before any private member, regardless of where they are in the class definition. In such a compiler, changing `class` for `struct` would break the system. – David Rodríguez - dribeas Jan 24 '11 at 17:58
  • @David - Are you sure? Aren't these rules the same for a struct? This is complete new to me. Any reference? – Tomas Jan 24 '11 at 18:08
  • They are the same for class or struct, the only difference on them is the default access specifier, but there is no guarantee that: `struct a { int x; protected: int y; };` and `class b { int x; protected: int y; };` will have the same layout. The reference would be in §9.2/12 "Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1)." – David Rodríguez - dribeas Jan 24 '11 at 19:20
  • Where *unspecified* means that a compiler can decide the order, and that allows a conforming compiler to move all *public* members together to the top (or the bottom) and all *private* members to the opposite end, and that can mean that the two structs in the last comment can yield different object layouts in a conforming compiler. – David Rodríguez - dribeas Jan 24 '11 at 19:22
2

No other differences but default access. Actually you may even write something like:

class X;

X* pX;

struct X {};

And it must compile.

Öö Tiib
  • 10,809
  • 25
  • 44
2

No. The difference between a struct and class is limited to the default accesibility of their members and inheritance. Both are public for struct and private for class

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
2

The difference between struct and class is just the default access level of the bases and attributes, and access levels are only verified at compile time, so you might be tempted to get some library edit the headers and change all class with struct to gain access to the internal details.

Don't

Compilers are not required to generate exactly the same code if you change the default access specifier. In particular this two classes could or not have the same memory layout, depending on the compiler:

struct a {
   int a;
private:
   int b:
};
class b {
   int a;
public:
   int b;
};

The reason is that the standard requires all member attributes to be laid out in memory in increasing positions within the same access qualifier. Compilers are allowed (I don't know any that does, but since this is not a requisite it may well change in the next version), to reorder the fields from different access blocks. A compiler could decide that public attributes come first, while private come at the end of the object, and that would mean that the position of fields a and b in the two classes would be swapped.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • I've run into this error though not because I switched class to struct or visa-versa. We're actually standardized on struct. What I did though was expose a single function and then forgot to upgrade the .lib for one of my modules. Luckily the resulting condition was uncompilable rather than resulting in weird behavior. – Edward Strange Jan 24 '11 at 17:59
  • I think that relying on a specific memory layout is generally a worse idea than sedding through your code to substitute struct with class or vice versa. – wilhelmtell Jan 25 '11 at 04:56
  • @wilhelmtell: I agree, but sometimes you do not notice. In particular, with the given example, if you take some library (the question talks about Ogre3D) that is precompiled and you modify the headers to gain access to the private members then your code and the library code think they talk about the same object, but when they refer to a member they refer to different bits in the object (and even possibly different sized objects if alignment requirements are not met in the new layout. It is not obvious that you are relying on the memory layout, but you do it every time you compile. – David Rodríguez - dribeas Jan 25 '11 at 08:42
  • 1
    in other words it violates ODR. – Yakov Galka Jan 25 '11 at 17:43
1

The only difference between structs and classes in C++ is that classes have private members and base classes by default. Normally changing class to struct shouldn't affect the generated machine code.

vitaut
  • 49,672
  • 25
  • 199
  • 336
  • "Base classes by default"? What do you mean? Structs can have a base, and so do classes, but you have to explicitly specify the base(s) in either case. – Seva Alekseyev Jan 24 '11 at 17:30
  • 1
    @Seva Alekseyev: I mean classes have "private base classes by default" (default access applies both to members and base classes). – vitaut Jan 24 '11 at 17:32
1

No, it was definitely not influenced by Java. Check the timeline. :)

Even if it doesn't do any more than control default visibility, that's still pretty meaningful. It somewhat becomes a matter of having the semantics available that allow you to say what you mean. The idea that, if you're using struct, then you're probably working within an older paradigm where public visibility is the only kind that would normally be thought of, and if you're using class, you're thinking in more OO terms where private visibility is held in higher esteem -- I dunno, makes sense to me dude.

chaos
  • 122,029
  • 33
  • 303
  • 309
1

There are people who try to use the 'struct' keyword to mean various things. For example, some people attempt to use struct to specify POD-ness or to be only data classes (classes with only public member variables and no functions).

In my opinion this is a serious mistake and all the reasons I've heard for it are flawed. For one thing, a keyword like struct is not sufficient to express the conditions they are attempting to use it to document. Since the keyword actually doesn't mean anything in particular people either accept this, or attempt to assert their own idea of what it should mean. There are too many incompatible opinions on what struct should mean in code for it to document any of them. You want to document things like, "This object must always be a POD," as clearly as possible instead of relying on obscure team standard details that can be difficult to remember. So, in order to document such a thing the only sufficient thing, honestly, is, // This object must always be a POD. It's clear, simple, and can't be misinterpreted by anyone who knows what a POD is, and this is well defined.

The best argument I've ever heard for using the keyword class instead of struct is that you should prefer private access to public access, revealing only that which is necessary. In other words, the "default" kind of inheritance and access exposure should be private until it is shown that more access is necessary. I agree with this opinion but I don't agree it is necessary to use the struct keyword to adhere to this principle.

Whatever one decides is going to be fairly arbitrary. Reasons can later be asserted for the decision but I find people who've chosen one or the other aren't easy to convince. I switched from 'class' to 'struct' because I read too many books on modern C++ and too much boost code; you'll rarely see the 'class' keyword in either. Truth be told, it doesn't matter; follow the standards of the team you are in at the time. In my opinion, adding a keyword that is essentially meaningless was a mistake.

Edit: Although, I do have to say that another reason I dislike using class is that it means too many things even while it also means nothing in particular. For example, you can use class instead of typename in template parameter specifications. Even if you use the class keyword you can pass any type and not necessarily any kind of class (like int). The only time I like to use the class keyword is where it actually does mean something and where you actually absolutely have to: specifying template template parameters.

Edward Strange
  • 40,307
  • 7
  • 73
  • 125
0

Hmm, now... If ever you put such a program into public space, say something like OSS, people will throw stones at you ;)

The struct keyword is kind of C heritage. And yes, the only difference (as far as I remember) is the default behaviour regarding members being protected.

Bjarne Stroustrup in "The C++ Programming Language":

By definition, a struct is a class in which members are by default public; that is

struct s { ...

is simply shorthand for

class s { public: ...

But the OO model is by far more than just encapsulation. It adds things like inheritance and member functions.

Community
  • 1
  • 1
thorsten müller
  • 5,621
  • 1
  • 22
  • 30
  • 1
    Structs can have inheritance and member functions. :) – Seva Alekseyev Jan 24 '11 at 17:56
  • Yes, that's what I say :) I just mentioned this, because of gokoon's last sentence: "Why add a keyword and try to impress programmers with the so called "OO model" while it's totally not enforced then?" Just to mention, that OO model is more than encapsulation (But you're right, now that I read it again it sounds a bit like only "class" would implement this. – thorsten müller Jan 25 '11 at 04:35
-1

struct exists for legacy reasons and that's it. You don't kill a kitten or anything anytime you use struct instead of class or indeed vice versa- they're the same thing, realistically, with a slightly different keyword and default.

Puppy
  • 144,682
  • 38
  • 256
  • 465