-2

It seems to me that C++-style struct can do more things than a C-style struct (for example, you can have member functions and access specifiers). What's the design reason for this, considering we already have class in c++?

A real design example would be appreciated.

henryyao
  • 1,758
  • 6
  • 23
  • 37

2 Answers2

1

What's the design reason for this, considering we already have class in c++?

A few potential benefits I can image are:

  • Easier compiler implementation by being able to handle structs and classes in almost the same way.
  • More options for developers. For instance, being able to use structs as more than just POD types by adding basic things like constructors, while leaving classes for usages where for object-oriented design is used.
  • Being able to derive from structs in C-compatible headers of 3rd-party libraries to add on convenience features like constructors and member functions.

A real design example would be appreciated.

Using the third idea: The Windows headers define a struct called RECT. MFC provides a class CRect which derives from it and provides several useful methods, but it's still able to be used in place of a RECT whenever needed by the Windows API.

TheUndeadFish
  • 8,058
  • 1
  • 23
  • 17
0

If you are asking for a "design reason" to allow members to be defaulted to public visibility, then this is easily justified: The legacy struct from C originally assumed all members were public, so defaulting to public would make it easier to port C code to C++ without heavy modifications to the original C code. It also makes it easier to share C header files with C++ code.

If you are asking why struct was extended in C++ to be allowed to have protected/private sections and methods, then this has more to do with what the inventor of C++ imagined to be the fundamental difference between a struct and a class from the point of view of a user of the language. The answer was ultimately made that fundamentally, there is really no difference whatsoever (save the default to public visibility).

jxh
  • 69,070
  • 8
  • 110
  • 193