C++ Classes – Object Oriented Programming

The C++ programming language is object oriented, in contrast to it’s predecessor, C, which was procedural. The Object Oriented approach states that every thing is an object of a Class. In C++, Classes are basically a collection of related variables and functions, under a common name.

A Class is commonly known as a Blueprint or template for an object. This template is then used to create and define an object, which we use in our program. Classes are never directly used, and they take up no memory, unlike objects.

There is no limit to the number of objects that can be created from a single template (class). Everything in C++, even data types like integers and floats are classes.


Understanding Classes in C++

Before we begin the actual code for C++ Classes, let us try to develop the concept of classes in you, and why we use them.

Classes bring together a bunch of variables and functions that are connected to each other under a single common name. Lets’ take as an example, a Class called “Car”. What kind of variables and methods might we want associated with this Class?

Well, for variables we might have “CarModel”, “HorsePower”, “Color” etc. For it’s methods, we might have “ChangeGear”, “Start”, “ActivateCooling” etc. The point of a Class is to compile all of these variables and functions and encapsulate them in a single block.

With other OOP concepts like Inheritance, we can create more complex relationships that exist between dozens of Classes.


Creating C+ Classes

Classes in C++ are created using the class keyword. The variables and methods within the class are enclosed by curly brackets, which defines the “Class Space”.

We’ll create some basic Classes here, and show you how their objects are created and accessed. In the example below, we create a Class called Car. It has 3 variables, and 2 methods inside it.

class Car {
    string CarModel;
    int HorsePower;
    float Speed;

public:
    void ChangeGears() {
        cout << "Change Gears" << endl;
    }
};

Forget the public keyword right now, we’ll explain that later.

Here, in the main function we make the object for the Car class called car1, then call the ChangeGears() method in it. The . operator denotes relationship. If you want to access any function or variable in an Object, you write a dot, then the name of the variable/function.

int main()  {
    Car car1 = Car();
    car1.ChangeGears();
}

Here we can see the output.

Change Gears

(A good IDE will give you dropdown list of variables/functions when you type in the .)


Access Levels

There are three Access Levels in C++, Private, Public and Protected. Access Levels are basically “Protection” levels, which state how much access is being allowed for a certain function/variable.

Access modes are used in two different situations. When defining member variables and functions, and when inheriting from classes. In this tutorial we’ll just discuss the first scenario, and leave the latter one for the actual inheritance tutorial.

Private:

The default Access Mode for most situations, because it’s the most secure option. The “Private” Access Mode means that only members within that class can access each other. Any attempt by external code to access private variables/methods with the private keyword, will be restricted.

In easier words, a private method/variable can only be accessed within the Class in which it was declared. Even Child Classes cannot access the private members from the Parent.

class Car {
private:
    string CarModel;
    int HorsePower;
    float Speed;
};

For private variables, we often make “setters” or “getters”, which allow external code to modify/get the values of the variable in question.

class Car {
    string CarModel;
    int HorsePower;
    float Speed;
};

As mentioned earlier, if you don’t include any keyword, private will be applied by default. Both code pieces over here are the exact same.


Public:

Public is an Access Mode setting where it basically “public” and accessible to anyone, inside or outside of the Class. Any variable can be accessed or modified and any function can be called.

class Car {
public:
    string CarModel;
    int HorsePower;
    float Speed;
};

Protected:

Protected is a rather special Access Mode used only during Inheritance of Classes. Sometimes we want our variables or methods to be private, but we want the Child Classes to be able to access them without making them public.

In such cases, we use the Protected Keyword on variables/functions in the Parent Class, which allows Child Classes to access them, while keeping them private for all other purposes.

class Car {
protected:
    string CarModel;
    int HorsePower;
    float Speed;
};

Accessors and Getters

You might wonder, that if the variables are private, then how are we to retrieve their values or set their values externally? There are several ways of doing this, such as using a Constructor (which we’ll discuss later) or through the use of Accessors and Getters.

The idea behind Accessors and Getters is to create public functions which can access the private data within the Class. These public functions serve as a sort of interface, which ensures a limited, but secure way for external code to access private data.

The below code has an accessor and a getter for the Speed variable. (you don’t need to make them for every private variable, only those that need them).

#include <iostream>
using namespace std;

class Car {
private:
    string CarModel;
    int HorsePower;
    float Speed;

public:
    void ChangeGears() {
        cout << "Change Gears" << endl;
    }

    void SetSpeed(float spd) {
        if (spd > 0) {
            this->Speed = spd;
        }
    }

    float GetSpeed() {
        cout << "Speed: " << Speed << endl;
        return Speed;
    }
};


int main()  {
    Car car1 = Car();
    car1.ChangeGears();
    car1.SetSpeed(10);
    car1.GetSpeed();
}

Output:

Change Gears
Speed: 10

Class Constructors

Constructors are another very integral part of Classes in C++. Constructors are a special type of function that run whenever the Object for a Class is made. Their primary job is to allocate memory to the Object being created (as Classes have no memory of their own).

There is always a constructor in every Class, even if you do not make one yourself. This is known as the Default Constructor. We can instead choose to define our version of the Constructor, which will perform it’s default job, as well as execute some custom code we write at runtime.

#include <iostream>
using namespace std;

class Car {

private:
    string CarModel;
    int HorsePower;
    float speed;

public:
    Car(string model, int hp, float spd) {
        this->CarModel = model;
        this->HorsePower = hp;
        this->Speed = spd;
    }

    void Display() {
        cout << this->CarModel << endl;
        cout << this->HorsePower << endl;
        cout << this->Speed << endl;
    }
};

We now call the Constructor, with the additional parameters.

int main()  {
    Car car1 = Car("ModelX", 800, 100.6);
    car1.Display();
}

The Output:

ModelX
800
100.6

Whenever you define your own Constructor, the “Default Constructor” gets removed. Remember to declare the Constructor as public, otherwise you won’t be able to create any objects for the Class. (Unless that’s what you want for some reason)


Using multiple Constructors

Something that you might not realize, is that you can have several constructors in a Class, allowing you to create objects in a variety of manners. For example, a Class may have a Null Constructor, and several Parameterized Constructors.

The below code shows this clearly.

#include <iostream>
using namespace std;

class Car {

private:
    string CarModel;
    int HorsePower;
    float Speed;

public:
    Car(string model, int hp, float spd) { // Parameterized Constructor
        this->CarModel = model;
        this->HorsePower = hp;
        this->Speed = spd;
    }

    Car(string model) {                   // Parameterized Constructor
        this->CarModel = model;
        this->HorsePower = 100;
        this->Speed = 80.5;
    }

    Car() {}                              // Null Constructor


    void Display() {
        cout << this->CarModel << endl;
        cout << this->HorsePower << endl;
        cout << this->Speed << endl;
    }
};

Do not confuse yourself between the Null Constructor and the Default Constructor. They are pretty much the same thing, but Default Constructor refers to the Constructor that is present in absence of any User-defined Constructor. Null Constructor is simply a Constructor with an empty body.

How we might create Objects for the above Class is shown in the Code below.

int main()  {
    Car car1 = Car("ModelX", 800, 100.6);
    Car car2 = Car("ModelX");
    Car car3 = Car();
}

All three of these are perfectly valid ways of creating Class Objects in C++.


There are many variants of the Constructor, such as the Copy Constructor and Assignment Constructor, which are a topic for another tutorial. Check the end of the article for a list of related links.


Constructor Initializer List

The Constructor Initializer List is another way of initializing data in a constructor. It has the exact same effect as what we did earlier, by using the Assignment operator to initialize the class data.

The logic behind doing something like CarModel(model), is that everything is an object, hence everything has a constructor. What we are really just doing is calling the String constructor for the object CarModel, which initializes it to whatever the value of model is.

#include <iostream>
using namespace std;

class Car {

private:
    string CarModel;
    int HorsePower;
    float Speed;

public:
    Car(string model, int hp, float spd) : CarModel(model), HorsePower(hp), Speed(spd) { }

    void Display() {
        cout << this->CarModel << endl;
        cout << this->HorsePower << endl;
        cout << this->Speed << endl;
    }
};


int main()  {
    Car car1 = Car("ModelX", 800, 100.6);
    car1.Display();
}

This is the output:

ModelX
800
100.6

Why we use the Constructor Initializer List

The Constructor initializer list is the first thing that runs during the Object creation, even before the Constructor itself. It purpose is to initialize constant Class data, which cannot be done normally within the constructor.

You can learn more about this by checking out this tutorial on the Initializer Lists in C++.


Further Reading

Object Oriented Programming is an massive world to take in, as it encompasses dozens of different concepts and features. We can’t explain everything in this tutorial, hence we have included links to the appropriate tutorials for the other Object Oriented Features in C++.

  1. Types of Constructors in C++
  2. Inheritance
  3. Polymorphism (Virtual and Over-riding)
  4. Copy and Assignment Constructors
  5. Friend Functions

This marks the end of the C++ Classes Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments