-1

When writing C++ code, what is the difference between using class and struct?

class Foo final { };

vs.

struct Bar final { };

When should I prefer one over the other? Is this merely a choice of programming/coding style?

  • 1
    What have your books, tutorials or class told you about it? – Some programmer dude Mar 26 '20 at 14:03
  • 3
    @Someprogrammerdude I can't find anything in my books that explains **why** I would want to use one over the other; it appears that they are practically identical. –  Mar 26 '20 at 14:04
  • 2
    That's because they *are* practically identical. The only difference between a `struct` and a `class` is the default visibility. A `struct` is by default `public`, while a class is by default `private`. Which one to choose very much depends on that. *Unless* you're making a C-compatible interface, and need your header file and structures to be compatible with C, in which case you need to use `struct` (and POD structures only, using non-C++ types for the members variables and no member functions). – Some programmer dude Mar 26 '20 at 14:07
  • 2
    A common convention is to use `struct` when you don't need anything other than public non-static member variables. Or when writing small helper types for templates, where `public` would waste space. – HolyBlackCat Mar 26 '20 at 14:11
  • 1
    In addition to what @SomeProgrammerDude said, there's *one* other difference. When you inherit from a `struct` the default is `public` inheritance and when you inherit from a `class` the default is `private` inheritance. – Jesper Juhl Mar 26 '20 at 14:47

1 Answers1

-5

A struct simply defines the layout of a piece of storage.

A class is a dynamically-allocated "thing" which can have methods ... it can do things.

Mike Robinson
  • 8,490
  • 5
  • 28
  • 41