views:

3368

answers:

14

This question was already asked in the context of C#/.Net.

Now I'd like to learn the differences between a struct and a class in (unmanaged) C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.

I'll start with an obvious difference:

  • If you don't specify public: or private:, members of a struct are public by default; members of a class are private by default.

I'm sure there are other differences to be found in the obscure corners of the C++ specification.

+16  A: 

Class' members are private by default. Struct's members are public by default. Besides that there are no other differences. Also see this question.

Kasprzol
Not only members, but all access, including inheritance.
Nemanja Trifunovic
Well, I'd say the other difference is semantics. Struct to many people makes them think "data structure" as a leftover from C.
Kris Kumler
This answer was accepted, but it's incomplete (and thus wrong). See: http://stackoverflow.com/questions/999779/what-are-the-differences-between-classes-and-structures-in-c/999798#999798
Assaf Lavie
A: 

Here is a good explanation: http://carcino.gen.nz/tech/cpp/struct_vs_class.php

So, one more time: in C++, a struct is identical to a class except that the members of a struct have public visibility by default, but the members of a class have private visibility by default.

nutario
A: 

Not in the specification, no. The main difference is in programmer expectations when they read your code in 2 years. structs are often assumed to be POD. Structs are also used in template metaprogramming when you're defining a type for purposes other than defining objects.

MSalters
+4  A: 

According to Stroustrup in the C++ Programming Language:

Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. I think of such classes as "not quite proper types, just data structures."

Functionally, there is no difference other than the public / private

crashmstr
That's wrong. There is a functional difference indeed.
Assaf Lavie
What difference? Please explain.
crashmstr
+2  A: 

The only other difference is the default inheritance of classes and structs, which, unsurprisingly, is private and public respectively.

Skizz

Skizz
A: 

It's just a convention. Structs can be created to hold simple data but later evolve time with the addition of member functions and constructors. On the other hand it's unusual to see anything other than public: access in a struct.

finnw
+16  A: 

Quoting The C++ FAQ,

[7.8] What's the difference between the keywords struct and class?

The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults.

struct and class are otherwise functionally equivalent.

OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.

Rob Adams
The FAQ is evidently wrong.
Assaf Lavie
+1  A: 

STRUCT is a type of Abstract Data Type that divides up a given chunk of memory according to the structure specification. Structs are particularly useful in file serialization/deserialization as the structure can often be written to the file verbatim. (i.e. Obtain a pointer to the struct, use the SIZE macro to compute the number of bytes to copy, then move the data in or out of the struct.)

Classes are a different type of abstract data type that attempt to ensure information hiding. Internally, there can be a variety of machinations, methods, temp variables, state variables. etc. that are all used to present a consistent API to any code which wishes to use the class.

In effect, structs are about data, classes are about code.

However, you do need to understand that these are merely abstractions. It's perfectly possible to create structs that look a lot like classes and classes that look a lot like structs. In fact, the earliest C++ compilers were merely pre-compilers that translates C++ code to C. Thus these abstractions are a benefit to logical thinking, not necessarily an asset to the computer itself.

Beyond the fact that each is a different type of abstraction, Classes provide solutions to the C code naming puzzle. Since you can't have more than one function exposed with the same name, developers used to follow a pattern of _(). e.g. mathlibextreme_max(). By grouping APIs into classes, similar functions (here we call them "methods") can be grouped together and protected from the naming of methods in other classes. This allows the programmer to organize his code better and increase code reuse. In theory, at least.

64BitBob
+3  A: 

One other thing to note, if you updated a legacy app that had structs to use classes you might run into the following issue:

Old code has structs, code was cleaned up and these changed to classes. A virtual function or two was then added to the new updated class.

When virtual functions are in classes then internally the compiler will add extra pointer to the class data to point to the functions.

How this would break old legacy code is if in the old code somewhere the struct was cleared using memfill to clear it all to zeros, this would stomp the extra pointer data as well.

KPexEA
Code that uses memfill to clear a struct probably has other offensive habits. Go with caution.
David Thornley
+1  A: 

1)The members of a structure are public by default, the members of class are private by default. 2)Default inheritance for Structure from another structure or class is public.Default inheritance for class from another structure or class is private.

class A{

public:

int i;

};

class A2:A{

};

struct A3:A{

};

struct abc{

int i;

};

struct abc2:abc{

};

class abc3:abc{ };

int _tmain(int argc, TCHAR argv[]) {

abc2 objabc;
objabc.i = 10;

A3 ob;
ob.i = 10;

   //A2 obja; //privately inherited
   //obja.i = 10;

  //abc3 obss;
  //obss.i = 10;

}

This is on VS2005.

+47  A: 

Gentlemen, you forget the tricky 2nd difference between classes and structs.

Quoth the standard (11.2.2):

In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class.

And just for completeness' sake, the more widely known difference between class and struct is defined in (11.2):

Member of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or union are public by default.

Assaf Lavie
Needs more upvotes, really.
Dan Olson
Here's a well-deserved upvote.
David Thornley
A: 

Here are some basic differences between Structs and Classes: http://developergeeks.com/article/21/difference-between-structs-and-classes

A: 

ISO IEC 14882-2003

9 Classes

§3

A structure is a class defined with the class-key struct; its members and base classes (clause 10) are public by default (clause 11).

Gregory Pakosz
A: 

It's worth remembering C++'s origins in, and compatibility with, C.

C has structs, it has no concept of of encapsulation, so everything is public.

Being public by default is generally considered a bad idea when taking an object-oriented approach, so in making a form of C that is natively conducive to OOP (you can do OO in C, but it won't help you) which was the idea in C++ (originally "C With Classes"), it makes sense to make members private by default.

On the other hand, if Stroustrup had changed the semantics of struct so that its members where private by default, it would have broken compatibility (it is no longer as often true as the standards diverged, but all valid C programs were also valid C++ programs, which had a big effect on giving C++ a foothold).

So a new keyword, class was introduced to be exactly like a struct, but public by default.

If C++ had come from scratch, with no history, then it would probably have only one such keyword. It also probably wouldn't have made the impact it made.

In general, people will tend to use struct when they are doing something like how structs are used in C; public members, no constructor (as long as it isn't in a union, you can have constructors in structs, just like with classes, but people tend not to), no virtual methods, etc. Since languages are as much to communicate with people reading the code as to instruct machines (or else we'd stick with assembly and raw VM opcodes) it's a good idea to stick with that.

Jon Hanna