14.2. What is a class?¶
In most object-oriented programming languages, a class is a user-defined type that includes a set of functions. As we have seen, structures in C++ meet the general definition of a class.
But there is another feature in C++ that also meets this definition;
confusingly, it is called a class. in C++, a class is just a
structure whose instance variables are private by default. For example,
I could have written the playing_card definition:
class playing_card
{
int m_suit, m_rank;
public:
playing_card ();
playing_card (int s, int r);
int rank () const { return m_rank; }
int suit () const { return m_suit; }
void rank (int r) { m_rank = r; }
void suit (int s) { m_suit = s; }
};
I replaced the word struct with the word class and removed the
private: label. This result of the two definitions is exactly the
same.
In fact, anything that can be written as a struct can also be
written as a class, just by adding or removing labels. There is no
real reason to choose one over the other, except that as a stylistic
choice, most C++ programmers use class.
Also, it is common to refer to all user-defined types in C++ as
“classes,” regardless of whether they are defined as a struct or a
class.
By default, the data members of a class are private.
How can we change deck, which is currently a struct, into a class?
struct deck {
private:
vector<card> cards;
public:
deck ();
deck (int n);
void print () const;
void swap_cards (int index1, int index2);
int find_lowest_card (int index);
void shuffle_deck ();
void sort_deck ();
deck subdeck (int low, int high) const;
deck merge_sort () const;
deck merge_sort (deck deck) const;
};
Private data members can be accessed within the class.