DEV Community

loading...
Cover image for Learn Object-Oriented Programming In C++

Learn Object-Oriented Programming In C++

Icheka Ozuru
A Senior Software Engineer who just wants to teach and develop software.
・9 min read

Learn Object-Oriented Programming In C++

Throughout our lives, we interact with objects. We see, we feel, we touch and manipulate. We pick things up and we drop them. We even describe our experiences with objects to other persons: we talk about attributes of objects we have interacted with in terms of their size, shape, color, weight or usefulness.

The idea of objects, their form, properties and value, is central to our existence as human beings. For example, we know that a car is red because we can identify the color red as one of its attributes. Just as we know that a rock is heavy because we can identify its weight as one of its properties.

This idea is the basis of Object-Oriented Programming practices. That is, data can be represented as objects that have attributes (which we call properties or props) and methods (which we also call member functions). Intrinsically, objects (in the real world and in the world of code) have values that can be deduced, depended upon and evaluated. We will see this momentarily.

For many students, the idea of objects and Object-Oriented Programming is a difficult one to grasp, often because there exists a "leap of faith" between the practice of procedural, logical, programming that they are used to and the "new" practice of objects and object-abstraction that OOP requires. Students are often scared to make this jump: "What if I don't get it quickly enough?" because the idea of representing data in their code as objects that can be interacted with (by the user of the system, the programmer, and even other objects) is strange.

This article aims to eradicate this fear, not entirely, because fear makes the journey of learning exciting, but just enough to help the reader make this leap. The concepts discussed here are simple enough for anybody to follow in any Object-Oriented language (not just C++). I will publish future versions of this article that will introduce the concepts again in other popular high-level languages like JavaScript, Java and Python.

The practice of Object-Oriented Programming grew out of the need for more effective ways of expressing the solution to many programming problems in terms of natural, real-world structures and processes. This new perspective makes problem-solving simpler, easier and less prone to bugs because problems, solutions and data can now be expressed in ways that every programmer is familiar with. Instead of talking about data in terms of bits and memory blocks, OOP encourages programmers to discuss their code in terms of real-life objects like fruits and stones. This is known as abstraction.

Objects As Structures

One of the first concepts I would like the reader to come to terms with is the idea of objects as structures. Structures are concrete matter. They have a noun by which they can be referred to (stone). This is their first attribute or property. They have mass (their second attribute or property) and they occupy space (their third property). A proper example is a stone as a structure. A stone has mass and can be weighed. It also occupies some space, which we call volume. This property can be more easily observed when a person drops a bit of stone in a bucket filled to the brim with a liquid, like water. Some liquid is displaced, and the volume of the displaced liquid is equal to the volume of the stone.
In order to properly represent a stone as data in a program, we will need to:

  1. Give our data structure a name.
  2. Give our data structure some mass.
  3. Give our data structure some volume.

We create objects in C++ (and in many other languages like JavaScript, Python, Java and PHP) using something called a class.
A class is simply a document where we write the properties and functions of our objects.

#include <string>
using namespace std;

class Stone {
    public:
        string mass;
        string volume;
};

int main() {
   return 0;
}
Enter fullscreen mode Exit fullscreen mode

It is the convention to name classes in camel-case.

We now have a class (which is just a place where we write the properties and functions of our objects) named "Stone" (first property) and having both mass and volume (second and third properties). For now, we have not assigned values to the mass and volume properties (i.e we haven't given the mass a value, like 10kg), but this is normal and we'll often have classes that just describe our objects but don't actually assign values to them. We often assign our values when we create objects of the class. This process is known as instantiation and we will see how in a bit.

Why 'public'?

You must have noticed the public keyword in our Stone class. What does it mean?
This particular keyword is an important part of creating classes. It allows us to define properties and functions that are accessible by functions or objects outside the class. Remember when I said objects can interact with other objects? They do this by accessing these public properties and functions. It is called public because the attributes it encapsulates are publicly-accessible. But we will see a bit of this soon.

Extending Our Stone Class

Our Stone class has two properties (albeit three attributes: its class name, and its two public properties). We can add a third and a fourth public property: color and texture.

#include <string>
using namespace std;

class Stone {
    public:
        string mass;
        string volume;
        string color;
        string texture;
};

int main() {
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Now we can describe any Stone object we instantiate from this class in four terms: mass, volume, color and texture. The good thing about this is that we can now have several stones in our program, each with its own unique properties. We can have a heavy stone and a light stone, a blue stone and a purple stone, a smooth stone and a rough stone. We can even add another property to our class (value_in_dollars) and have expensive stones (like sapphires, for example) and cheap stones (like gravel).

#include <string>
using namespace std;

class Stone {
    public:
        string mass;
        string volume;
        string color;
        string texture;
        int value_in_dollars;
};

int main() {
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Instantiation: making objects from classes

Instantiation is the process of declaring a new object based on the properties and methods (functions) of a class.

Instantiation is the final step in creating objects and we use it every time we perform operations in programming. The truth, which I feel very guilt-stricken about keeping from you for this long, is that data types (like integers and strings and vectors) are all classes that we instantiate from standard classes that come pre-packaged with the language.
Let's see how this works by, first, looking at constructors.

Object Constructors

An object constructor is a special function that is executed each time instantiation occurs. In plain English, this compiles to: constructors are special functions that are run whenever an object is created from a class. They are useful for two major reasons:

  1. They make it possible for the programmer to perform certain operations on objects or on data in the program for every object that is instantiated.
  2. They make it easier to individualize objects so that, although two objects were instantiated from the same class, they have different properties and can behave in different, albeit predictable, ways.

In real life, every human has several properties that make him or her unique. A person can be 1.6 meters tall, light-skinned, red-haired, and have a large nose. These are all properties of this person. Her friend can be 1.7 meters tall, dark-skinned, dark-haired, and have a small nose. Despite their differences, these two persons have the same characteristics. They have:
1. Height
2. Complexion
3. Hair color
4. Nose size

So how do we express this difference in code, especially in OOP code?

Instantiation

The process of instantiation is a pretty straightforward one. We instantiate using the new keyword. Like so:

#include <string>
using namespace std;

class Person {
    public:
        string name;
        float height;
        string complexion;
        string hair_color;
        string nose_size;
};

int main() {
    // instantiation
    Person person_1;
    Person Anna;
    Person Bella;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

You might notice how I use Person just like I would use int or string or float. Remember how I 'confessed' earlier that I had been hiding something from you? This is it: the classes that you make are data types. Object-Oriented Programming is really about expressing real-world objects as data structures. Object-Oriented Programming gives you the freedom and the power to define your own data types. You are not limited by types int, float and char. As a matter of fact, one fundamental difference between C++ and C is the addition of a new data type: string. The class that makes this possible (string) is written right there in the Standard C++ Library. If this isn't neat, I don't know what is.

The classes that you make are data types.

Individualism Using Constructors

We have learned how to instantiate new objects from our classes using the new keyword. OOP takes this freedom further by giving us the ability to individualize our objects. In real life, we have nearly 8 billion individual Persons, and each person is unique. One property that makes a person unique is his (/her) name. This name is often assigned at, or soon after, birth. In the case of our code, the constructor function allows us to access the events that take place at the birth (or construction) of our objects. We can give our persons names using the constructor function so that each person is 'born' with a unique name.

#include <string>
#include <iostream>
using namespace std;

class Person {
    public:
        string name;
        float height;
        string complexion;
        string hair_color;
        string nose_size;
        Person(string birth_name) {
            name = birth_name; // makes the person's name the name he is given at birth
        }
};

int main() {
    Person Anne("Anne");
    cout "Anne's name is " << Anne.name << endl;
    // Anne's name is Anne
}
Enter fullscreen mode Exit fullscreen mode

In C++ we create constructors by naming them after their classes.

#include <string>
#include <iostream>
using namespace std;

class Stone {
    public:
        string kind;
        float weight;
        float value_in_dollars;
        // constructor below
        Stone(string kind, float value) {
            kind = kind;
            value_in_dollars = value;
        }
};

int main() {
    Stone my_sapphire("sapphire", 3120.00);
    cout << my_sapphire.value_in_dollars << endl;
    // 3120.00
    cout << my_sapphire.kind << endl;
    // sapphire
}
Enter fullscreen mode Exit fullscreen mode

Final Section: Member Functions

The final lesson we'll see in this article is member functions and how they relate with the concept of objects.

A member function (also called a "method") is a function defined within a class. In clearer terms, a member function is an operation that objects of a class have access to. They can call these functions, get return values from them, and use them to manipulate the data within that instance of the class (i.e within the object itself).

Member functions are important because they allow programmers to express actions and processes after real-life counterparts. For example, people speak, hear and think. We can define these verbs in our Person class like so:

#include <string>
#include <iostream>
using namespace std;

class Person {
    public:
        string name;
        float height;
        string complexion;
        string hair_color;
        string nose_size;
        Person(string birth_name) {
            name = birth_name; // makes the person's name the name he is given at birth
        }

        void speak(string speech) {
            cout << this.name << " says: " << speech << endl;
        }

        void listen(string speech) {
            cout << "You said '" << speech << "'" << endl;
        }
};

int main() {
    Person Anne("Anne");
    Anne.speak("The weather is hot today, don't you agree?");
    // Anne says: The weather is hot today, don't you agree?
    Anne.listen("What will you do this weekend?");
    // You said 'What will you do this weekend?'
}
Enter fullscreen mode Exit fullscreen mode

Member functions can also be used to change the data within the object (this data is called state).

#include <string>
#include <iostream>
using namespace std;

class Person {
    public:
        string name;
        float height;
        string complexion;
        string hair_color;
        string nose_size;
        Person(string birth_name) {
            name = birth_name; // makes the person's name the name he is given at birth
        }

        void changeName(string new_name) {
            this->name = new_name;
        }

        void listen(string speech) {
            cout << "You said '" << speech << "'" << endl;
        }
};

int main() {
    Person Anne("Anne");
    Anne.speak("The weather is hot today, don't you agree?");
    // Anne says: The weather is hot today, don't you agree?
    Anne.listen("What will you do this weekend?");
    // You said 'What will you do this weekend?'
}
Enter fullscreen mode Exit fullscreen mode

There you go! I hope that you have seen how easy and useful Object-Oriented Programming is, and that you have made your leap of faith. This isn't all there is, but it is enough to help you write applications for simple problems by yourself. If you really, really want to master Object-Oriented Programming, I recommend that you take some time to read about the subject. In particular, W3Schools has a nice tutorial on the subject. It's very simple and concise. You can find it here.
Also, Bruce Eckel's Thinking In C++ is an excellent book about the language. I found it a bit verbose, and it does seem targeted at the mid-level to advanced programmer (but not necessarily a C++ programmer), but there is so much insight to gain and Bruce shares his vast wealth of experience liberally.

Don't hesitate to reach out to me if you need any help at all. I can be reached via email at rhemafortune@gmail.com. I'll email you back as soon as possible.

May the Code be with us all.
Cheers.

Discussion (0)