Classes & Objects in C++

·

9 min read

Classes & Objects in C++

Understanding what classes are and how they work in C++ will save you a lot of time from writing your code in the functional way. This is because classes are object-oriented in nature and provide you with all the benefits of OOP such as encapsulation, inheritance, polymorphism, abstraction.

Classes move you up a notch in your journey to learning C++ and can be used in writing code that is well structured without everything been thrown into the main() function and regular functions

Table of Contents

1. What is a Class?

2. Data Members & Member functions

3. Access Modifiers

4. Creating your first class

5. Constructors & Destructors

6. Accessors & Mutators

7. What are Objects?

8. Creating an object for your class

9. A simple program using the class you created

What is a Class?

A class is an Abstract Data Type (ADT), that is, it is a data type which is created by the programmer. It is a collection of related objects and it defines the data members (variables), and member functions (methods). In other words, we can say that a class is a template or a blueprint for something and it defines what you want to do with that said blueprint.

It is important to note that, just because a class is a collection of related objects does not mean that you can only store data of one type. No, this is what makes classes fun to work with because you can have multiple data members of different data types. When a class is defined, the C++ complier does not allocate any memory to it until an object is created.

Doesn’t that sound cool? Having the ability to create your own data type and using it? That is one of the many interesting aspects of OOP as it provides you, the programmer, the ability to tell your program you want it to do.

Data Members & Member Functions

A data member is a variable that can either be of a basic data type such as int, string, char, float or double or it can be of an ADT nature. Data members are sometimes referred to as state, properties or attributes and they represent the data fields with their current values.

Member functions are the actions, the behaviour that tell the compiler what operations you want to perform on the data members of that particular class. These are just functions that belong to a class, there is really nothing super special about them.

It is important to note that all members of a class by default are set to private, this will be explained shortly.

Access Modifiers

This is where encapsulation comes in. Access modifiers allow you to define how members of a class can be accessed. Do you want them to be private, public or protected? These terms help in the overall data hiding of your data from the user as it is important to always keep certain things hidden from the user and only reveal some.

Private Access Modifier, this tells the complier that you do not want anything outside the class to have access to your variables. Since by default all members of a class are set to private, whether you decide to explicitly make your members private is all up to you.

Public Access Modifier, these allows for others outside the class to have access to these members and can therefore use them. However, the only way to have full access to them is through the use of an object which has full access. Public members can easily access the private members even outside the class as they full access to the members.

Protected Access Modifiers, on the other hand work like both the private and public modifiers. They have a limited access to the members of a class. Take this example, in the company you work for, certain information such as projects are usually just known by a certain group of people like the Project manager and the team members. However, other people in the company can also be aware of what you are doing but have limited knowledge about what exactly what you are doing and anyone outside the company has no knowledge of what you are doing. That means that the information is protected, not fully private to the team members alone but not also public to the outside world.

The order of how you write you access modifiers is really important. Just because all members of a class by default are private does not mean that you use the public keyword first and then add the other members assuming they are going to be private by default. This is why most C++ programmers always start with defining the private members first using the private keyword and then followed by protected and then public. In this case, the order would not matter when you use the reserved keyword to explicitly tell the complier the level of encapsulation you want.

Creating Your First Class

In order for you to create a class in C++, you need to note a few things. First, a class is not a function, secondly, a class is a statement in its own right and needs to be terminated using a semicolon, and lastly, it is good practice to name your classes using Pascal Notation (capitalise the first letter of each word e.g., StudentType).

Now that you know that, let us create our first class and give it data members and member functions. The class will be called Student and will hold a student’s names, age, test score, programming score and course grade. From this, we can tell that we need to calculate the student’s course grade using their test score and programming score and we can come up with the following member functions: getData(), printData(), and calculateScore(). getData() will be used to get the student’s details such as their first and last name, their test score and programming score. The printData() will be used to just print out everything and the calculteScore() will be used to calculate the student’s course grade using their programming and test scores.

Therefore we can define our class as follows:

class Student 
{
      // data members
      private:
            string firstName, lastName;
            char courseGrade;
            int testScore, programmingScore;

    // members functions
     public:
          void getData();
          void calculateScore();
          void printData() const;
};

Constructors & Destructors

Constructors: a constructor for lack of better words is a special function that does not have a return type and has the same name as the class name. It’s main purpose is simply to initialise ALL the data members of the class to something but mostly to their default values, this is true for the default constructor. These are of three types: default constructor, constructor with parameters and a copy constructor which is used to copy one object into another object.

Destructors: destructors are used to destroy an object when it is no longer needed. It also has the same name as the class thereby making it a special class function.

Accessor & Mutators

Accessors: also known as getters and are used to get information that will be stored in the class’s members. They usually include a const keyword because they are not meant to change any of the values but only display or get and store them.

Mutators: also know as setters are used to set the initialise the members of an object. They almost work the same way as constructors; however, they do not set the class’s members to their initial values.

What are Objects?

An object is an instance of a class. What this means is that an object brings the class to life by modelling the class in real life. It contains data and functions that operate on that data. This is where memory allocation happens by the compiler.

A single class can have more than one object; each having access to the same data members and member functions. One object can be used to model the class in one perspective while the other can be used to model the same class in another perspective. One house blueprint can be used to model houses of various sizes, that is what objects do.

Creating an Object for your Class

When creating an object, you need to first introduce the class name as that object’s data type. This tells the compiler that the variable you have just created is not a regular variable and that it is an object. In so doing, the compiler is now able to allocate memory space that is large enough to store all the variables you had initially created in your class.

Below is how we would go about creating an object of the Student data type:

Student newStudent;

There are five steps to remember when creating an object and these are;

  1. Object is created
  2. Object is initialised
  3. Operations on the object
  4. Clean out the object when no longer needed
  5. Recycled by the destructor.

A simple program using the created Class

Combining what we have learnt so far, we can create a full C++ program using the class Student to help us get the student’s details, calculate their course grade and then print out the information they have provided us with.

#include <iostream>
using namespace std;

class Student 
{
    private:
        string firstName, lastName;
        int testScore, programmingScore;
        char courseGrade;

    public:
        void getData();
        char calculateScore();
        void printData() const;
};

void Student::getData()
{
    cout << "Enter first name: ";
    cin  >> firstName;
    cout << "Enter last name: ";
    cin  >> lastName;
    cout << "Enter test score: ";
    cin  >> testScore;
    cout << "Enter programming score: ";
    cin  >> programmingScore;
}

void Student::printData() const
{
    cout << "The information entered is as follows.\n";
    cout << "--------------------------------------\n";
    cout << "First name is: " << fName << endl;
    cout << "Last name is: " << lName << endl;
    cout << "Test score: " << testScore << endl;
    cout << "Programming score: " << programmingScore << endl;    
}

char Student::calculateScore()
{
    int score;
    score = (programmingScore + testScore) / 2;

    if (score >= 90)
        courseGrade = 'A';
    else if (score >= 80)
        courseGrade = 'B';
    else if (score >= 70)
        courseGrade = 'C';
    else if (score >= 60)
        courseGrade = 'C';
    else 
        courseGrade = 'F';

    return courseGrade;
}

int main()
{
    Student newStudent; // object newStudent of type Student

    newStudent.getData();
    newStudent.printData();

   char myGrade = newStudent.calculateScore();
   cout << "Your course grade is: " << myGrade << endl;

   return 0;
}

Note that you can call the calculateScore() function inside the printData() function for more encapsulation. There are many ways in which this program can be written and you can experiment with it. The above code can also be separated into different files and then simply called in the main() function as a better way of following OOP principles.

Conclusion

Classes are vital in C++ and knowing the correct syntax is very important as they help save you time when creating code for applications that have the same information. This helps with code resuse.

Connect with me on Twitter

Connect with me on LinkedIn