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 ?
The only difference between structs and classes in C++ is that classes have private members and base classes by default. Normally changing
class
tostruct
shouldn't affect the generated machine code.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":
But the OO model is by far more than just encapsulation. It adds things like inheritance and member functions.
Actually,
class
andstruct
are both checked at compile time. The only difference is whether the default for members who you've not explicitly specified the access for arepublic
(for astruct
) orprivate
(for aclass
). 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.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.