Search

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:

2020/10/16

Classes

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 are very much like data-only structs, except that classes provide much more power and flexibility. 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 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:

2020/10/16

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 same capabilities. 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.

Conclusion

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!

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

93 comments to 8.2 — Classes and class members

  • heyjuhua

    HI alex may I ask when you say we are already using member function of std::string and std::vector ..etc why do we not need to defined a object for them like we do for class and struct ? thanks

  • Hamed O.Khaled

    Hi Alex!
    why declaring this variable caused errors in the compilation ?

    • Alex

      extern in this context means this is a forward declaration of variable x that is defined in some other file.

      But in this program, it is not defined in some other file, so the program doesn’t link.

  • anufa

    #include<iostream>
    using namespace std;
    struct student
    {
        int rollnum;
        string name;
        float marks;
        
    void print();

    };

    void student::print()
    {
        cout << rollnum << name << marks;
    }
    student my={2,"anum fatima",99.99};
    int main()
    {
        my.print();
        cout << endl << endl;    
        cout << sizeof(my);
    }

    hi Alex!!
    there are two queries related to this little piece of code
    one is , if classes provide opportunity to use data members and methods on a same platform (as being encapsulated) then with structs i can also do the same .. as i used data members declarations and use of functions in structs instead of class and my code is still working ..
    second query is that why my compiler that is dev c++ giving me the size of struct 24 ?? and with what respect ??

    • Alex

      Yes, in C++ structs and classes are almost identical. However, many people feel it was a bad decision to make structs able to act like classes, so best practice is now to use classes when you have functions, and use structs when you’re data-only. This way it’s clear whether your object will clean up after itself (class: yes, struct: no).

      You’re getting a struct size of 24 because that’s apparently the sizeof(int) + sizeof(std::string) + sizeof(float), plus any memory used for alignment/padding on your machine.

  • BADRI

    sir.. why you aren’t using namespace std?

  • Omri

    Hello Alex,
    Pls clarify, do we declare variables or define them?
    In the following quoted paragraph from above, are the sugested modification of text (or additions), placed in parentheses, correct?
    "…In C++, when we define (declare) a variable of a (type corresponding to a defined) class (in short, class type), 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 (declaring) 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…"

    • Alex

      You can both declare variables and define them. Which you do depends on your intent.

      Declaring a variable (via a forward declaration) simply tells the compiler that it exists, so it can do type checking. A declaration does not actually create the variable.

      Defining a variable (which is what you do most of the time with variables) actually creates the variable and allocates memory for it.

      A variable is only instantiated when it is defined (not declared).

  • If I were to declare two variables with the same name but using different classes, how would the compiler figure out which variable I am referring to when I use it in other places around the program?

  • Milos

    Hey Alex,

    I was just wondering maybe you know what are the most important diffrences on Xcode and Visual Studio, or maybe you know some site where i can look up to it. This is really important to me so pls answer.

    Thanks, Milos.

  • Deepti

    Also, Alex or anyone, I want to practice more programming questions on C++ from basics to advanced(oops). Can anyone share the websites? Preferably, if there are solutions to it, then will be great.
    I tried to browse over net but unable to find specifically for C++ that includes control statement, loops, arrays, pointers,strings,oops etc.. questions.

    Thanks in advance.

    • abdelaziz

      hello Deepti,
      check this one https://www.hackerrank.com
      and search for c++ track
      try to solve the problem and if you couldn’t solve it open the Discussions tab
      good luck 🙂

  • Deepti

    Hi Alex,

    I have a question in the first struct example. The function
    void print(DateStruct &date)
    {
        std::cout << date.year << "/" << date.month << "/" << date.day;
    }

    has a parameter ‘&date’. Does this imply the parameter is passed by address? Because if the date parameter given without & and it still works

  • Mohammad

    hello, there is a typo in the below sentence, it says "that that" instead of "that".

    Consequently, we recommend using the struct keyword for data-only structures, and the class keyword for defining objects that that require both data and functions to be bundled together.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter