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 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:


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.


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(1, 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

111 comments to 8.2 — Classes and class members

  • Pashka2107

    Hi Alex,
    May I suggest a small quiz for this lesson?

    1. Create a class IntPair, which holds two public integer variables m_first and m_second. Write a set(int, int) function, which returns void, takes two integer parameters and copy them into m_first and m_second. Also, write a print() function, which prints m_first and m_second to the console.
    The following code must compile:

    …and produce output:


    Suggested solution:

    2. Whether IntPair should be a class?

    Suggested solution:
    Since structs are typically used when dealing with data-only structures, class is more suitable here, as IntPair holds functions as well.

  • vysyaraju yaswanth kumar

    Hi Alex,

    Can you please help me understanding this sentence:

    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.

    • nascardriver

      Hi vysyaraju!
      A struct is usually used for the single purpose of holding data. Whatever happens to that data is up to the coder.
      A class is also used to hold data, but it also has functions associated with that data, this includes functions that dynamically allocate and free memory.
      When you create a struct and manually allocate memory in it then you’re responsible for freeing that memory.
      If you have a class then that class will usually allocate that memory on it’s own and upon destruction free that memory.

    • Alex

      Yes, but it’s a bit hard without having covered constructors and destructors yet.

      Basically, any well-written class will have a function called a destructor that is executed when the class is destroyed. This destructor function can do any kind of cleanup necessary to return resources to the system (deallocate memory, close a file or database, disconnect from a network, etc…)

      Although structs can have destructors, in practice they most often don’t (if you want/need to use a destructor, use a class, not a struct). Therefore, if a struct is managing any kind of resource, it’s not safe to just assume it will clean up when the struct is destroyed. It may, but it may not.

  • Sam

    Dear Mr. Alex!
    God bless!!! God Bless!!! God Bless!!!
       It is not  typing error that i wish God to bless you 3 times! It is a matter of satisfaction about your amazing tutorial among the once i ever seen before. I have discovered many web sites and i have downloaded many books.But only your tutorial gives me a key to get through programing from down the scratch!
      I also thank you for my sister to recommend me to read your tutorial. B/s she is able to  know  who is the best. (she is a post doctoral researcher in computer science in Europe.)
       Dear Alex You are helping my country Ethiopia (Africa)through helping me!
    I like the way you treated people honestly,for all who share you their difficulties.  
    God bless!!! God Bless!!! God Bless!!!

  • kamil

    Hi alex I love your tutorial I just want to ask if I will be able to create app with this knowledge because I am only aware of creating a calculator 🙁

    • Alex

      You’ll be able to create simple console apps. More importantly, this will give you the foundation to go out and learn other stuff, including frameworks that will help you create graphical apps.

      • kamil

        Thank you for your answer! I want to ask if after completing this whole websites tutorials I will be able to create a button that you can click on or not… or some kind of cool visual thing.  Thank you!

        • Alex

          No -- these tutorials don’t cover graphical user interfaces, because those are not part of the core C++ language. However, once you have completed these tutorials, you should have enough knowledge to learn a graphical user interface platform (e.g. QT or wxwidgets). Consider these lessons a prerequisite.

  • Ran

    Hi Alex:

    Is that possible to write a code like this:

    today is an instance and it call functionA(). Then it call another functionB.

    Or functionA() is not a "function"?

    • Alex

      Yes, it is possible! If functionA() returns an object for which functionB() is a valid member function, then functionB() will be called on the return value of functionA()!

      We talk about this more later in this chapter (or maybe the next one?).

  • Michael

    Hi Alex,
    what do you mean by "Unlike normal functions, the order in which member functions are defined doesn’t matter!"?  I have difficulty figuring out its meaning by context.

    • Alex

      With normal functions, a function can’t call a function that’s defined “below” it (without a forward declaration):

      With member functions, this limitation doesn’t apply:

  • Benard

    Hi Alex,

    Why Am I getting 1 error on uniform initialization stage when I run this program.

    #include <iostream>

    struct DateStruct
        int year;
        int month;
        int day;

    void print(DateStruct &date)
        std::cout << date.year << "/" << date.month << "/" <<;

    int main()
        DateStruct today { 2020, 10, 14 }; // use uniform initialization = 16; // use member selection operator to select a member of the struct

        return 0;

    My compiler is suggesting a ";" between "DateStruct today" and "{2020,10,14};"

    • Alex

      What compiler are you using? If you’re using an older compiler, or C++11 compatibility is disabled, uniform initialization won’t work.

      • Sunny

        Sorry, I am posting a question by clicking reply to some random question.
        So please clarify, Structs and classes are same?
        Apart from one difference that class can clean up itself, is there no other difference?

        • Alex

          Yes, they’re essentially the same. However, by convention, how they are used typically differs, with structs being used as plain-old-data structures, and classes being used for objects.

  • 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

    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()
        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.


    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
      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 << "/" <<;

    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