-2

I have basic knowledge of structures from C, and as far as I'm aware, classes and structs are not exactly the same, but the c++ primer defines a "class" using the struct keyword starting on p. 72-73. Here's a small excerpt with the code:

"Defining the Sales_data Type

Although we can’t yet write our Sales_item class, we can write a more concrete class that groups the same data elements. Our strategy for using this class is that users will be able to access the data elements directly and must implement needed operations for themselves.Because our data structure does not support any operations, we’ll name our version Sales_data to distinguish it from Sales_item. We’ll define our class as follows:"

struct Sales_data {
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};

This book is suppose to be an authoritative overview of C++11, so why would they use the keyword struct instead of class to describe a class type?

Spellbinder2050
  • 644
  • 3
  • 13
  • 1
    A `struct` is a `class`. – NathanOliver Apr 29 '21 at 13:20
  • 5
    [The authors of that book describe why here](https://www.oreilly.com/library/view/c-primer-fifth/9780133053043/ch07lev2sec6.html) _"As a matter of programming style, when we define a class intending for all of its members to be public, we use struct. If we intend to have private members, then we use class."_ – acraig5075 Apr 29 '21 at 13:30
  • _As far as I'm aware but haven't really checked_? See the description of a [`class-key`](https://en.cppreference.com/w/cpp/language/classes) in the class declaration grammar. – Useless Apr 29 '21 at 13:31
  • *and as far as I'm aware, classes and structs are not exactly the same* -- They are the same. Whatever you can do in a `class` you can do in a `struct`, and vice-versa. – PaulMcKenzie Apr 29 '21 at 13:49
  • A `struct` and a `class` are functionally identical in C++, with the only exceptions being that default access to members and for inheritance is `private` for a `class` and `public` for a `struct`. – Peter Apr 29 '21 at 14:21

1 Answers1

1

It's common use to define POD types as struct and data types which contain other members, constructors, methods, etc. as class. They are basically the same, the difference being the members are public by default in a struct and private by default in a class.

The usage in the book is consistent with the above description.

anastaciu
  • 23,467
  • 7
  • 28
  • 53