Introduction to Classes in C++

In the previous unit, we covered structs and discussed how they are great for bundling multiple member variables into a single object that can be initialized and passed around as a unit. In other words, structs provide a convenient package for storing package and moving related data values.

Consider the following struct:

#include <iostream>

struct Date
{
    int day{};
    int month{};
    int year{};
};

void printDate(const Date& date)
{
    std::cout << date.day << '/' << date.month << '/' << date.year; // assume DMY format
}

int main()
{
    Date date{ 19, 11, 23 }; // initialize using aggregate initialization
    printDate(date);        // can pass entire struct to function

    return 0;
}

In the above example, we create a Date object and then pass it to a function that prints the date. This program prints:

19/11/23

The class invariant problem

Perhaps the biggest difficulty with structs is that they do not provide an effective way to document and enforce class invariants. we defined an invariant as , “a condition that must be true while some component is executing”.

Introduction to Classes

Just like structs, a class is a program-defined compound type that can have many member variables with different types.

Defining a class

Because a class is a program-defined data type, it must be defined before it can be used. Classes are defined similarly to structs, excepts we use the class keyword instead of struct. For example, here is a definition for a simple employee class:

class Employee
{
    int m_id {};
    int m_age {};
    double m_wage {};
};