views:

7916

answers:

25

In what scenarios is it better to use a struct vs a class in C++?

+2  A: 

At the risk of being out-of-my-element for C++-specific concerns in this issue, I'll share from my background of C#/Ruby/Java:

Use a struct if you just need a container of related data; use a class if you need mechanisms for operating on that related data internally.

Brian Warshaw
You're spot-on. I personally believe that the other language designers borrowed this idiom from C++ developers.
Tom
+48  A: 

The only difference between a class and a struct in C++ is that structs have default public members and bases and classes have default private members and bases. Both classes and structs can have a mixture of public and private members, can use inheritance, and can have member functions.

I would recommend using structs as plain-old-data structures without any class-like features, and using classes as aggregate data structures with private data and member functions.

Commodore Jaeger
Interesting, indeed. Thanks for this.
Brian Warshaw
A struct with no modifiers or methods is called a POD struct, which exists as a backwards compatible interface with C libraries as it is (supposedly) guaranteed to be laid out as though it were a C struct. Apart from this one exception though, the only difference is as stated.
workmad3
@workmad3: The name is misleading, but 9/4 (C++03) says: "A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor." There is no restriction on using the "struct" class-key and no restriction on using "public" (see 8.5.1/1 for aggregate requirements). This is not a difference between "struct" and "class".
Roger Pate
@Commodore: Your use of "aggregate" could be misunderstood, given the standard's definition. :)
Roger Pate
+1  A: 

For C++, there really isn't much of a difference between structs and classes. The main functional difference is that members of a struct are public by default, while they are private by default in classes. Otherwise, as far as the language is concerned, they are equivalent.

That said, I tend to use structs in C++ like I do in C#, similar to what Brian has said. Structs are simple data containers, while classes are used for objects that need to act on the data in addition to just holding on to it.

Andy
+1  A: 

They are pretty much the same thing. Thanks to the magic of C++, a struct can hold functions, use inheritance, created using "new" and so on just like a class

The only functional difference is that a class begins with private access rights, while a struct begins with public. This is the maintain backwards compatibility with C.

In practice, I've always used structs as data holders and classes as objects.

enigmatic
+2  A: 

One place where a struct has been helpful for me is when I have a system that's receiving fixed format messages (over say, a serial port) from another system. You can cast the stream of bytes into a struct that defines your fields, and then easily access the fields.

typedef struct
{
    int messageId;
    int messageCounter;
    int messageData;
} tMessageType

void processMessage(unsigned char *rawMessage)
{
    tMessageType *messageFields = (tMessageType *)rawMessage;
    printf("Id is %d\n", messageFields.messageId);
}

Obviously, this is the same thing you would do in C, but I find that the overhead of having to decode the message into a class is usually not worth it.

mbyrne215
The same can be achieved in C.
HMage
Or you could just implement `operator >>` on a class instead of writing the `processMessage` function, which would make your C++ look more like proper C++ and less like C.
Nick Bastin
+1  A: 

To answer my own question (shamelessly), As already mentioned, access privileges are the only difference between them in C++.

I tend to use a struct for data-storage only. I'll allow it to get a few helper functions if it makes working with the data easier. However as soon as the data requires flow control (i.e. getters/setters that maintain or protect an internal state) or starts acquring any major functionality (basically more object-like), it will get 'upgraded' to a class to better communicate intent.

ZeroSignal
+4  A: 
argv0
That is not the correct usage of POD. A struct (or class) can be POD struct if (and only if) it contains ONLY POD members.
Martin York
"predictable copying semantics": The symantics are the same as for class (and have the same problems (shallow copy)).
Martin York
A: 

I never use "struct" in C++.

I can't ever imagine a scenario where you would use a struct when you want private members, unless you're willfully trying to be confusing.

It seems that using structs is more of a syntactic indication of how the data will be used, but I'd rather just make a class and try to make that explicit in the name of the class, or through comments.

E.g.

class PublicInputData {
    //data members
 };
Baltimark
According to me, a "syntactic indication of how data will be used" is a perfectly good reason to use a struct, especially if the alternative is to use a comment or a name in the classname.
Viktor Sehr
+6  A: 

The only time I use a struct instead of a class is when declaring a functor right before using it in a function call and want to minimize syntax for the sake of clarity. e.g.:

struct Compare { bool operator() { ... } };
std::sort(collection.begin(), collection.end(), Compare());
Ferruccio
That's what I would have written.
Martin York
thats how I use it aswell nowadays
Viktor Sehr
Love the example. You get my up-vote.
Allbite
A: 

I find that I rarely use struct in C++, except when I need auto aggregate initialization of Plain Old Data, I don't think that can be done with data structures defined with an instance of a class.

Roger Nelson
A: 

One More difference between C++: struct Vs Classes, you cannot use protected as an access specifier in structure while in case of Class you can.

Yes you can. You should test claims like this before writing them. Delete before somebody marks you down a point.
Martin York
+1  A: 

I believe that there is no serious reason for using structs in C++. To me structs are another redundant "feature" of C++ that exists only for compatibility with C, like typedefs. These would not exist if C++ was not initially treated as an extension to C, and was designed from scratch, such as Java. In general, I find that many of the weirdest things about C++ have to do with C compatibility.

Kostas
+5  A: 

In practice, most people seem to use class if they plan on having member functions, and struct if they don't. This is really just a convention, however. struct and class are actually pretty much identical, except that class defaults to private access, wile struct defaults to public access.

Laurence Gonsalves
Conventions are incredibly important (consider the impact of iterator categories, or header guards, or .cxx/.h file pairs). This answer downplays that importance, and thus is less useful than most of the others.
Tom
I wouldn't say my answer "downplays" the importance of convention. I think it's important to know what's convention and what's really part of the language if you want to be more than just a cargo-cult programmer.
Laurence Gonsalves
+1  A: 

they're the same thing with different defaults (private by default for class, and public by default for struct), so in theory they're totally interchangeable.

so, if I just want to package some info to move around, I use a struct, even if i put a few methods there (but not many). If it's a mostly-opaque thing, where the main use would be via methods, and not directly to the data members, i use a full class.

Javier
+1  A: 

Structs by default have public access and classes by default have private access.

Personally I use structs for Data Transfer Objects or as Value Objects. When used as such I declare all members as const to prevent modification by other code.

anio
+10  A: 

Struct - For POD (plain old data) and all member accessibility is public.

Class - When you need better encapsulation and need member functions to work with the class's state.

Appu
This is true only by convention. There is no difference, apart from default encapsulation.
Dave Hillier
@Dave - that convention is the most important reason to do this. If it is followed consistently, that single difference immediately provides a lot of information to readers.
Tom
+15  A: 

As everyone else notes there are really only two actual language differences:

  • struct defaults to public access and class defaults to private access.
  • When inheriting from them struct defaults to public inheritance and class defaults to private inheritance. (Ironically, as with so many things in C++, the default is backwards: public inheritance is by far the more common choice, but people rarely declare structs just to save on typing the "public" keyword.

But the real difference in practice is between a class/struct that declares a constructor/destructor and one that doesn't. There are certain guarantees to a "plain-old-data" POD type, that no longer apply once you take over the class's construction. To keep this distinction clear, many people deliberately only use structs for POD types, and, if they are going to add any methods at all, use classes. The difference between the two fragments below is otherwise meaningless:

class X
{
  public:

  // ...
};

struct X
{
  // ...
};

(Incidentally, here's a thread with some good explanations about what "POD type" actually means: What are POD types in C++?)

quark
Nice example regarding the inheritance differences: [here](http://blog.stevedoria.net/20050913/differences-between-cpp-classes-and-structs).
Liran Orevi
+2  A: 

From the C++ FAQ:

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.

http://www.parashift.com/c++-faq-lite/classes-and-objects.html#faq-7.8

Tal Pressman
+1  A: 

I thought that Structs was intended as a Data Structure (like a multi-data type array of information) and classes was inteded for Code Packaging (like collections of subroutines & functions)..

:(

GaiusSensei
A: 

I use struct only when I need to hold some data without any member functions associated to it (to operate on the member data) and to access the data variables directly.

Eg: Reading/Writing data from files and socket streams etc. Passing function arguments in a structure where the function arguments are too many and function syntax looks too lengthy.

Technically there is no big difference between class and struture except default accessibility. More over it depends on programming style how you use it.

harik
A: 

Technically both are the same in C++ - for instance it's possible for a struct to have overloaded operators etc.

However :

I use structs when I wish to pass information of multiple types simultaneously I use classes when the I'm dealing with a "functional" object.

Hope it helps.

#include <string>
#include <map>
using namespace std;

struct student
{
    int age;
    string name;
    map<string, int> grades
};

class ClassRoom
{
    typedef map<string, student> student_map;
  public :
    student getStudentByName(string name) const 
    { student_map::const_iterator m_it = students.find(name); return m_it->second; }
  private :
    student_map students;
};

For instance, I'm returning a struct student in the get...() methods over here - enjoy.

Maciek
A: 

As every one says, the only real difference is the default access. But I particularly use struct when I don't want any sort of encapsulation with a simple data class, even if I implement some helper methods. For instance, when I need something like this:

struct myvec {
    int x;
    int y;
    int z;

    int length() {return x+y+z;}
};
ogoid
A: 

When would you choose to use struct and when to use class in C++?

I use struct when I define functors and POD. Otherwise I use class.

// '()' is public by default!
struct mycompare : public std::binary_function<int, int, bool>
{
    bool operator()(int first, int second)
    { return first < second; }
};

class mycompare : public std::binary_function<int, int, bool>
{
public:
    bool operator()(int first, int second)
    { return first < second; }
};
AraK
A: 

You can use "struct" in C++ if you are writing a library whose internals are C++ but the API can be called by either C or C++ code. You simply make a single header that contains structs and global API functions that you expose to both C and C++ code as this:

// C access Header to a C++ library
#ifdef __cpp
extern "C" {
#endif

// Put your C struct's here
typedef struct foo
{
    ...
};
// NOTE: the typedef is used because C does not automatically generate
// a typedef with the same name as a struct like C++.
typedef struct foo foo;

// Put your C API functions here here
void bar(foo *fun);

#ifdef __cpp
}
#endif

Then you can write a function bar() in a C++ file using C++ code and make it callable from C and the two worlds can share data through the declared struct's. There are other caveats of course when mixing C and C++ but this is a simplified example.

Adisak
A: 

1 more difference i found between the Struct and the Class is that the former is a value type and later is the reference type.

Optimist
The question is tagged C++, and in C++ there is no such thing as value and reference types. Any variable of any type can be referred to by pointer or passed around as a value.
David Thornley