8.2 — Classes and class members

While C++ provides a number of fundamental data types (e.g. char, int, long, float, double, etc…) that are often sufficient for solving relatively simple problems, it can be difficult to solve complex problems using just these types. One of C++’s more useful features is the ability to define your own data types that better correspond to the problem being solved. You have already seen how enumerated types and structs can be used to create your own custom data types.

Here is an example of a struct used to hold a date:

Enumerated types and data-only structs (structs that only contain variables) represent the traditional non-object-oriented programming world, as they can only hold data. In C++11, we can create and initialize this struct as follows:

Now, if we want to print the date to the screen (something we probably want to do a lot), it makes sense to write a function to do this. Here’s a full program:

This program prints:



In the world of object-oriented programming, we often want our types to not only hold data, but provide functions that work with the data as well. In C++, this is typically done via the class keyword. Using the class keyword defines a new user-defined type called a class.

In C++, classes and structs are essentially the same. In fact, the following struct and class are effectively identical:

Note that the only significant difference is the public: keyword in the class. We will discuss the function of this keyword in the next lesson.

Just like a struct declaration, a class declaration does not declare any memory. It only defines what the class looks like.

Warning: Just like with structs, one of the easiest mistakes to make in C++ is to forget the semicolon at the end of a class declaration. This will cause a compiler error on the next line of code. Modern compilers like Visual Studio 2010 will give you an indication that you may have forgotten a semicolon, but older or less sophisticated compilers may not, which can make the actual error hard to find.

Just like with a struct, to use a class, a variable of that class type must be declared:

In C++, when we define a variable of a class, we call it instantiating the class. The variable itself is called an instance, of the class. A variable of a class type is also called an object. Just like how defining a variable of a built-in type (e.g. int x) allocates memory for that variable, instantiating an object (e.g. DateClass today) allocates memory for that object.

Member Functions

In addition to holding data, classes (and structs) can also contain functions! Functions defined inside of a class are called member functions (or sometimes methods). Member functions can be defined inside or outside of the class definition. We’ll define them inside the class for now (for simplicity), and show how to define them outside the class later.

Here is our Date class with a member function to print the date:

Just like members of a struct, members (variables and functions) of a class are accessed using the member selector operator (.):

This prints:


Note how similar this program is to the struct version we wrote above.

However, there are a few differences. In the DateStruct version of print() from the example above, we needed to pass the struct itself to the print() function as the first parameter. Otherwise, print() wouldn’t know what DateStruct we wanted to use. We then had to reference this parameter inside the function explicitly.

Member functions work slightly differently: All member function calls must be associated with an object of the class. When we call “today.print()”, we’re telling the compiler to call the print() member function, associated with the today object.

Now let’s take a look at the definition of the print member function again:

What do m_year, m_month, and m_day actually refer to? They refer to the associated object (as determined by the caller).

So when we call “today.print()”, the compiler interprets m_day as today.m_day, m_month as today.m_month, and m_year as today.m_year. If we called “tomorrow.print()”, m_day would refer to tomorrow.m_day instead.

In this way, the associated object is essentially implicitly passed to the member function. For this reason, it is often called the implicit object.

We’ll talk more about how the implicit object passing works in detail in a later lesson in this chapter.

The key point is that with non-member functions, we have to pass data to the function to work with. With member functions, we can assume we always have an implicit object of the class to work with!

Using the “m_” prefix for member variables helps distinguish member variables from function parameters or local variables inside member functions. This is useful for several reasons. First, when we see an assignment to a variable with the “m_” prefix, we know that we are changing the state of the class. Second, unlike function parameters or local variables, which are declared within the function, member variables are declared in the class definition. Consequently, if we want to know how a variable with the “m_” prefix is declared, we know that we should look in the class definition instead of within the function.

By convention, class names should begin with an upper-case letter.

Rule: Name your classes starting with a capital letter.

Here’s another example of a class:

This produces the output:

Name: Alex  Id: 1  Wage: $25
Name: Joe  Id: 2  Wage: $22.25

Unlike normal functions, the order in which member functions are defined doesn’t matter!

A note about structs in C++

In C, structs can only hold data, and do not have associated member functions. In C++, after designing classes (using the class keyword), Bjarne Stroustrup spent some amount of time considering whether structs (which were inherited from C) should be granted the ability to have member functions. Upon consideration, he determined that they should, in part to have a unified ruleset for both. So although we wrote the above programs using the class keyword, we could have used the struct keyword instead.

Many developers (including myself) feel this was the incorrect decision to be made, as it can lead to dangerous assumptions: For example, it’s fair to assume a class will clean up after itself (e.g. a class that allocates memory will deallocate it before being destroyed), but it’s not safe to assume a struct will. Consequently, we recommend using the struct keyword for data-only structures, and the class keyword for defining objects that require both data and functions to be bundled together.

Rule: Use the struct keyword for data-only structures. Use the class keyword for objects that have both data and functions.

You have already been using classes without knowing it

It turns out that the C++ standard library is full of classes that have been created for your benefit. std::string, std::vector, and std::array are all class types! So when you create an object of any of these types, you’re instantiating a class object. And when you call invoke a function using these objects, you’re calling a member function.


The class keyword lets us create a custom type in C++ that can contain both member variables and member functions. Classes form the basis for Object-oriented programming, and we’ll spend the rest of this chapter and many of the future chapters exploring all they have to offer!

Quiz time

1a) Create a class called IntPair that holds two integers. This class should have two member variables to hold the integers. You should also create two member functions: one named “set” that will let you assign values to the integers, and one named “print” that will print the values of the variables.

The following main function should execute:

and produce the output:

Pair(1, 1)
Pair(2, 2)

Show Solution

(h/t to reader Pashka2107 for this quiz idea)

1b) Why should we use a class for IntPair instead of a struct?

Show Solution

8.3 -- Public vs private access specifiers
8.1 -- Welcome to object-oriented programming

161 comments to 8.2 — Classes and class members

  • lucieon

    can you explain what you mean by "it’s fair to assume a class will clean up after itself, but it’s not safe to assume a struct will."?

    • Alex

      By convention, classes have destructors (functions that execute when the object is destroyed) that will clean up anything that needs to be cleaned up. By "clean up", I mean things like deallocating memory, closing files, disconnecting from networks, etc... Structs may or may not do these things (often not).

  • Hi Alex!

    "classes are very much like data-only structs"
    Shouldn't this be the other way around?
    "structs are very much like data-only classes"

    • Alex

      I see what you're getting at. I've altered the sentence to read, "In C++, classes and structs are essentially the same". Thanks for the feedback.

  • Ryan

    1. How could I improve this?
    2. I tried using vectors instead of dynamic arrays but couldn't get it to work. How would you do this using vectors instead of dynamic arrays

    Any help would be appreciated.

    • Hi Ryan!

      Your code doesn't compile because of lines 20 and 21.
      array[1] doesn't exist. @array has only 1 element.
      There's no point in dynamically allocating @array if you know it's size at compile time.

      Fix these and share your new code so I can change your code to use vectors.

      • Ryan

        Thanks for the help!

  • W

    "For example, it’s fair to assume a class will clean up after itself (e.g. a class that allocates memory will deallocate it before being destroyed), but it’s not safe to assume a struct will."

    Could you please explain further about why it's not safe to assume a struct will clean up after itself? Under my impression, C++ struct also has a default constructor. C++ struct and class are identical apart from the default state of the accesses specifiers.

    • Alex

      Mainly due to the way they are conventionally used. Although structs _can_ clean up after themselves just as well as classes, common usage is to use a struct to move data (no member functions), so typically a struct won't do any cleanup (because that would require a destructor).

      • W

        Thanks for your reply. So if we define a data only struct, there will be no default constructor/destructor when instantiated. If we define a struct with member functions, there will be default constructor/destructor automatically when instantiated. Am I right? How about class If we define a data only class?

        • Alex

          Not quite -- if you define a data only struct or class, it will have a default constructor and destructor that won't do anything.

          Structs are normally used for moving data (and thus don't have any associated functions, even though the compiler may implicitly generate some) whereas classes are treated as complete objects that have setup and cleanup routines.

  • Ryder

    In construction a class

    Should we define all the varibles out of memeber functions?

    I think it is not. Because I can define some varibles in the mumeber functions, and it works.

    My questions, is this a good practice? Or, Should we avoid define varibles within a member function?

    If you can not understand me, please let me know.

    Here I make an example:

    My question is `int m_test = 2;` a bad programming habit?

    • Alex

      In general, there's nothing wrong with using local variables in a member function. Use them just like you would for non-member functions (e.g. when you don't need their values to persist beyond the scope of the function).

      The way you've used it here doesn't make sense though, since print() gets called for each employee, and your "We have 2 employees" statement will get printed twice.

      • Ryder

        Is the following thought a bad programming habit?

        Accessing a local variable in a member function of a class
        from another class.

        For example, I want to access `people` ( in the class 'Employee')
        from another class as shown in the flowing code:

        The class `Boss` is shown in the following code:

        Is that possible to access the local variable ( people.x ) in
        `Employee::print()` from an object of class 'Boss' ? Or, is this
        a bad thought? Is there any other method to achieve this thought?

Leave a Comment

Put all code inside code tags: [code]your code here[/code]