1091
votes

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

26
This isn't only applicable to C++, but to any language that provides both structs and classes.Jason Bunting
I still disagree - I approach this question semantically. Maybe there are some technical differences, but semantically, they are not. Structs are really useful for creating value types, classes are not.Jason Bunting
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
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.Navaneeth K N
This is true only by convention. There is no difference, apart from default encapsulation.Dave Hillier

26 Answers

926
votes

The differences between a class and a struct in C++ is:

  • struct members and base classes/structs are public by default.
  • class members and base classes/struts are private by default.

Both classes and structs can have a mixture of public, protected and private members, can use inheritance and can have member functions.

I would recommend you:

  • use struct for plain-old-data structures without any class-like features;
  • use class when you make use of features such as private or protected members, non-default constructors and operators, etc.
259
votes

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, 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++?)

224
votes

There are lots of misconceptions in the existing answers.

Both class and struct declare a class.

Yes, you may have to rearrange your access modifying keywords inside the class definition, depending on which keyword you used to declare the class.

But, beyond syntax, the only reason to choose one over the other is convention/style/preference.

Some people like to stick with the struct keyword for classes without member functions, because the resulting definition "looks like" a simple structure from C.

Similarly, some people like to use the class keyword for classes with member functions and private data, because it says "class" on it and therefore looks like examples from their favourite book on object-oriented programming.

The reality is that this completely up to you and your team, and it'll make literally no difference whatsoever to your program.

The following two classes are absolutely equivalent in every way except their name:

struct Foo
{
   int x;
};

class Bar
{
public:
   int x;
};

You can even switch keywords when redeclaring:

class Foo;
struct Bar;

(although this breaks Visual Studio builds due to non-conformance, so that compiler will emit a warning when you do this.)

and the following expressions both evaluate to true:

std::is_class<Foo>::value
std::is_class<Bar>::value

Do note, though, that you can't switch the keywords when redefining; this is only because (per the one-definition rule) duplicate class definitions across translation units must "consist of the same sequence of tokens". This means you can't even exchange const int member; with int const member;, and has nothing to do with the semantics of class or struct.

57
votes

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()); 
41
votes

From the C++ FAQ Lite:

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.

23
votes

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("MessageId 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.

22
votes

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
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
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.

19
votes

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;}
};
11
votes

Structs (PODs, more generally) are handy when you're providing a C-compatible interface with a C++ implementation, since they're portable across language borders and linker formats.

If that's not a concern to you, then I suppose the use of the "struct" instead of "class" is a good communicator of intent (as @ZeroSignal said above). Structs also have more predictable copying semantics, so they're useful for data you intend to write to external media or send across the wire.

Structs are also handy for various metaprogramming tasks, like traits templates that just expose a bunch of dependent typedefs:

template <typename T> struct type_traits {
  typedef T type;
  typedef T::iterator_type iterator_type;
  ...
};

...But that's really just taking advantage of struct's default protection level being public...

10
votes

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.

10
votes

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.

5
votes

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.

5
votes

An advantage of struct over class is that it save one line of code, if adhering to "first public members, then private". In this light, I find the keyword class useless.

Here is another reason for using only struct and never class. Some code style guidelines for C++ suggest using small letters for function macros, the rationale being that when the macro is converted to an inline function, the name shouldn't need to be changed. Same here. You have your nice C-style struct and one day, you find out you need to add a constructor, or some convenience method. Do you change it to a class? Everywhere?

Distinguishing between structs and classes is just too much hassle, getting into the way of doing what we should be doing - programming. Like so many of C++'s problems, it arises out of the strong desire for backwards compatability.

5
votes

As others have pointed out

  • both are equivalent apart from default visibility
  • there may be reasons to be forced to use the one or the other for whatever reason

There's a clear recommendation about when to use which from Stroustrup/Sutter:

Use class if the class has an invariant; use struct if the data members can vary independently

However, keep in mind that it is not wise to forward declare sth. as a class (class X;) and define it as struct (struct X { ... }). It may work on some linkers (e.g., g++) and may fail on others (e.g., MSVC), so you will find yourself in developer hell.

4
votes

Class.

Class members are private by default.

class test_one {
    int main_one();
};

Is equivalent to

class test_one {
  private:
    int main_one();
};

So if you try

int two = one.main_one();

We will get an error: main_one is private because its not accessible. We can solve it by initializing it by specifying its a public ie

class test_one {
  public:
    int main_one();
};

Struct.

A struct is a class where members are public by default.

struct test_one {
    int main_one;
};

Means main_one is private ie

class test_one {
  public:
    int main_one;
};

I use structs for data structures where the members can take any value, it's easier that way.

4
votes

Both struct and class are the same under the hood though with different defaults as to visibility, struct default is public and class default is private. You can change either one to be the other with the appropriate use of private and public. They both allow inheritance, methods, constructors, destructors, and all the rest of the goodies of an object oriented language.

However one huge difference between the two is that struct as a keyword is supported in C whereas class is not. This means that one can use a struct in an include file that can be #include into either C++ or C so long as the struct is a plain C style struct and everything else in the include file is compatible with C, i.e. no C++ specific keywords such as private, public, no methods, no inheritance, etc. etc. etc.

A C style struct can be used with other interfaces which support using C style struct to carry data back and forth over the interface.

A C style struct is a kind of template (not a C++ template but rather a pattern or stencil) that describes the layout of a memory area. Over the years interfaces usable from C and with C plug-ins (here's looking at you Java and Python and Visual Basic) have been created some of which work with C style struct.

3
votes

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.

3
votes

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.

1
votes

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.

1
votes

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; }
};
1
votes

I use structs when I need to create POD type or functor.

1
votes

All class members are private by default and all struct members are public by default. Class has default private bases and Struct has default public bases. Struct in case of C cannot have member functions where as in case of C++ we can have member functions being added to the struct. Other than these differences, I don't find anything surprising about them.

1
votes

Just to address this from a C++20 Standardese perspective (working from N4860)...

A class is a type. The keywords "class" and "struct" (and "union") are - in the C++ grammar - class-keys, and the only functional significance of the choice of class or struct is:

The class-key determines whether ... access is public or private by default (11.9).

Data member default accessibility

That the class keyword results in private-by-default members, and `struct keyword results in public-by-default members, is documented by the examples in 11.9.1:

class X { int a; // X::a is private by default: class used

...vs...

struct S { int a; // S::a is public by default: struct used

Base class default accessibility

1.9 also says:

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

Circumstances where consistent use of struct or class is required...

There's a requirement:

In a redeclaration, partial specialization, explicit specialization or explicit instantiation of a class template, the class-key shall agree in kind with the original class template declaration (9.2.8.3).

...in any elaborated-type-specifier, the enum keyword shall be used to refer to an enumeration (9.7.1), the union class-key shall be used to refer to a union (11.5), and either the class or struct class-key shall be used to refer to a non-union class (11.1).

The following example (of when consistency is not required) is provided:

struct S { } s; class S* p = &s; // OK

Still, some compilers may warn about this.


Interestingly, while the types you create with struct, class and union are all termed "classes", we have...

A standard-layout struct is a standard layout class defined with the class-key struct or the class-key class.

...so in Standardese, when there's talk of a standard-layout struct it's using "struct" to imply "not a union"s.

I'm curious if there are similar use of "struct" in other terminology, but it's too big a job to do an exhaustive search of the Standard. Comments about that welcome.

0
votes

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.

-5
votes

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)..

:(

-8
votes

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
 };