8.2 — Classes and class members

While C++ provides a number of basic data types (eg. 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 worked upon. 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. If you want to initialize or manipulate this data, you either have to do so directly, or write functions that take a DateStruct as a parameter:

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 structs, except that classes provide much more power and flexibility. In fact, the following struct and class are effectively identical:

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

Just like a struct definition, a class definition 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.

In order to use a class, a variable of that class type must be declared:

In C++, when we declare 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.

Member Functions

In addition to holding data, classes can also contain functions! Here is our Date class with a function to set the date:

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

Note that in the original struct version of SetDate(), we needed to pass the struct itself to the SetDate() function as the first parameter. Otherwise, SetDate() wouldn’t know what DateStruct we wanted to work on.

However, in our class version of SetDate(), we do not need to pass cToday to SetDate()! Because SetDate() is being called on cToday, the member variables in SetDate() will refer to the member variables of cToday! Thus, inside function SetDate(), m_nDay is actually referring to cToday.m_nDay. If we called cTomorrow.SetDate(), m_nDay inside of SetDate() would refer to cTomorrow.m_nDay.

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.

Here’s another example of a class:

This produces the output:

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

Warning: One of the most common C++ mistakes is to forget to end all class (and struct) declarations with a semicolon. This can cause the compiler to report all sorts of weird, seemingly-unrelated errors!

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

49 comments to 8.2 — Classes and class members

  • Bogdan


    - char *strName is equivalent to char strName[] ?
    - strName shouldn't be szName ?

  • sudha

    Develop a payroll application to compute the salary for the employees in an organization. Class Employee has general information namely employee_id, employee name, department_name, address, mobile number and email?id. There are two types of employees such as training professionals and regular employees. The Definition of Pay_calculate() will be different for different types of employees. Include suitable menu for navigating the application.
    Training professionals has total teaching experience, qualification, no_of_sessions_handled.
    Salary = no_of_sessions_handled*one_day_salary (Both can be randomized values)
    Regular employees has department they belong to, basic_pay, designation
    Gross Pay = basic_pay+HRA+DA Net Pay = Gross Pay – PF
    HRA = 9% of Basic Pay, DA = 90% of Basic Pay, PF = 20% of Basic Pay
    SNo Designation Basic_Pay
    1 Manager 30000
    2 Technical Lead 25000
    3 Senior Software Engineer 20000
    4 Software Engineer 15000
    • Get and display details of different types of employees using operator overloading(<>)

    • Write suitable exceptions for the given scenario .
    • Write a friend function LiseDeptWise() to list all employees for a given department_name.

  • Isaac_Michelsen

    The following program was made mostly by copypasting the authers code and flags 3 compiler errors:
    /home/isaac/c++/tests/main.cpp|16|error: ‘cToday’ does not name a type|
    /home/isaac/c++/tests/main.cpp|17|error: ‘cToday’ does not name a type|
    /home/isaac/c++/tests/main.cpp|18|error: ‘cToday’ does not name a type|
    ||=== Build finished: 3 errors, 0 warnings (0 minutes, 0 seconds) ===|


    class Date
    int m_nMonth;
    int m_nDay;
    int m_nYear;

    Date cToday; // declare a variable of class Date

    // Assign values to our members using the member selector operator (.)
    cToday.m_nMonth = 10;
    cToday.m_nDay = 14;
    cToday.m_nYear = 2020;

    using namespace std;

    int main()
    int x = cToday.m_nDay;

    cout << x << endl;
    return 0;

  • Sagaryal21

    void SetDate(DateStruct &sDate, int nMonth, int nDay, int Year)
    sDate.nMonth = nMonth;
    sDate.nDay = nDay;
    sDate.nYear = nYear;

    DateStruct sToday;

    // Init our date to the same date using the function
    SetDate(sToday, 10, 14, 2020);

    Mr Author I Have a problem in the first argument of the function declared a struct variable using '&' sign.......but i couldn't understand it why you used it..........i tried in my IDE without using & sign but it displayed error: "saying Warning 1 warning C4700: uninitialized local variable 'sToday' used" ..........what does this mean.......and you passed sToday structure into the function.....does that mean the name sToday is an address itself.....Please help me with this......





  • pranesh

    class Employee
    char m_strName[25];
    int m_nID;
    double m_dWage;

    // Set the employee information
    void SetInfo(char *strName, int nID, double dWage)
    strncpy(m_strName, strName, 25);
    m_nID = nID;
    m_dWage = dWage;

    // Print employee information to the screen
    void Print()
    using namespace std;
    cout << "Name: " << m_strName << " Id: " <<
    m_nID << " Wage: $" << m_dWage << endl;

    int main()
    // Declare two employees
    Employee cAlex;
    cAlex.SetInfo("Alex", 1, 25.00);

    Employee cJoe;
    cJoe.SetInfo("Joe", 2, 22.25);

    // Print out the employee information

    return 0;

    this is the last example of this chapter. can u tell me why have we used a pointer *strname as a parameter in setinfo function.what if we do not use a pointer?

  • wblakenc

    I hope you figured out the issue with the sample code if not, or possibly to help others confused one thing was left out of the code snip. At the top of the file using 'strncpy' you need to include "string.h". It should show: #include

  • anismizi

    Dear Alex,
    I just copied your code into my codeblocks compiler. But it is showing the following errors.
    C:\Users\ANIS\Desktop\C++ practice\text.cpp||In member function 'void Employee::SetInfo(char*, int, double)':|
    C:\Users\ANIS\Desktop\C++ practice\text.cpp|12|error: 'strncpy' was not declared in this scope|
    C:\Users\ANIS\Desktop\C++ practice\text.cpp||In function 'int main()':|
    C:\Users\ANIS\Desktop\C++ practice\text.cpp|30|warning: deprecated conversion from string constant to 'char*'|
    C:\Users\ANIS\Desktop\C++ practice\text.cpp|33|warning: deprecated conversion from string constant to 'char*'|
    ||=== Build finished: 1 errors, 2 warnings ===|

  • gans

    Hi Alex,
    Not sure if you still respond to the queries here,
    I'd a query, as I understand, there are no significant differences b/w struct and classes except access specifiers. then Why did we have separate datatype class? we could have use struct in C++.
    Please share your thoughts.

  • Yashar

    I can not understand what is the advantage of "class" relative to "struct".
    It seems they both do the same thing.
    Whether advantage of the class is reduction of defined functions out of the main() ?

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">