Broad Network


C++ OOP Basics

C++ Taking the Bull by the Horns – Part 23

Forward: In this part of the series, we look at C++ OOP basics. OOP stands for Object Oriented Programming.

By: Chrysanthus Date Published: 22 Aug 2012

Introduction

This is part 23 of my series, C++ Taking the Bull by the Horns. In this part of the series, we look at C++ OOP basics. OOP stands for Object Oriented Programming.

When you have a set of object identifiers and functions that work together and would appear in many parts of your code, you can put all that in one generalized unit called a class. There will be no need for repeat typing of the set. In this tutorial, we are talking about a set of object identifiers and functions. In one of the previous tutorials, we talked about a set of statements that forms a function. Here, we are talking about a set of object identifiers and functions that form a class. The functions work with the values of the object identifiers. Under that condition, it is possible that the values of the object identifiers and the results of the accompanying functions can be changing. In order to use the class, you have to create a particular unit from the class, everything being equal. That particular unit is called an object. In this part of the series, I give you the basic explanation of C++ classes and objects. An object produced from a class, is a kind of derived object.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Group of object identifiers and Functions
Let us consider a group of object identifiers and functions that would work as a generalized unit. Read and try the following code and note that it returns the sum of 2 and 3.

#include <iostream>
using namespace std;

int num1 = 2;
int num2 = 3;

int add(int no1, int no2)
    {
        int sum = no1 + no2;
        return sum;
    }

int result = add(num1, num2);

int main()
    {
        cout << result;
        return 0;
    }

You have two object identifiers (num1 and num2) and a function (add). In the code, the function is called, and the returned sum is held in the object identifier, result. The result is sent to the output in the main function.

Now the above code sums just two numbers, which are 2 and 3. You would want a piece of code that sums any two numbers, not just 2 and 3. One possibility is to include another function that would receive the two numbers, change the values of the two object identifiers, then call the add(no1, no2) function. There is another possibility, which has become very popular over the years; it is to create a class, then create an object from the class that would add any two particular numbers.  A class is a generalized unit of code, from which things call objects can be created to do particular task. An object is called the Instance of a class. Note: in the above code the two identifiers (num1 and num2) and the function (add), work together. That is why it is advisable to have the two identifiers and the function in one unit called a class.

Class
A class is a generalized unit from which objects can be instantiated (created). A class is basically a code unit that has object identifiers and functions that work together. The object identifiers are called properties and the functions are called methods. A class itself cannot solve a problem; that is, a class itself cannot carry out a task. It is an object created from a class that carries out a task; not the class.

There is a nuance here. You have objects such as fundamental object Type objects and you have objects created from a class. The context in this tutorial should tell you the kind of object we are referring to.

When you create an object from a class, we say you are instantiating the object. Properties and methods of a class are called members of the class. An object created from a class has the same members as the class.

A Class and Object created from the above Code
The above code can be converted into a class and object as follows:

#include <iostream>
using namespace std;

class Calculator
    {
        public:
        int num1;
        int num2;

        int add ()
            {
                int sum = num1 + num2;
                return sum;
            }
    };



int main()
    {
        Calculator myObject;
        myObject.num1 = 2;
        myObject.num2 = 3;
        int result = myObject.add();
        cout << result;

        return 0;
    }

You define a class beginning with the reserved word, class. Then you have a space and then follow it with the name of the class. You chose whatever name you want to give for the class. I have given the name Calculator because the class is doing some calculation. After the class name, you have a pair of curly brackets. There are statements and even blocks inside the curly brackets. After the closing curly bracket, you have a semicolon; this is because the creation of a class is a statement similar to the creation of a struct. All the statements for the class go inside the braces. It is conventional to type the object identifiers first before the functions. The object identifiers in the class are called properties (of the class) and the functions in the class are called methods. Both properties and methods are called members. In the creation of a basic class as the ones we are considering in this article, you precede the statements in the class with the reserved word, public and a colon. The object identifiers and the function we had in the previous code are the same object identifiers and functions we now have in the class.

Read through the creation of the class above to appreciate how a class is created.

Under normal circumstances, you define the properties (object identifiers) in a class, and you do not initialize them. That is why in the above class, num1 and num2 do not have any values assigned to them. There is what is called constructor function that can be used to assign initial values to them, as an object is being created from a class (see below).

Creating an Object from the Class without Constructor function
A class like the one above does not have a constructor function (see below). When a class does not have a constructor function, you create an object from it just as you create an object of a fundamental type. You begin with a class name, then a space, then an identifier name that you chose to identify the object; then a semicolon to form a statement. The first statement in the main function above is an application of this; it is the instantiation of the object, myObject, an identifier name, which I gave; you can give whatever name you want.

Using an Object
The aim of our class and object is to solve the problem, which the first code above solved. It is to add two numbers that are in two int objects. You cannot use a class, you use but objects created from the class. Members of a class automatically become members of the instantiated object. You can create many objects from a class; the main thing you need is different identifier names for the objects. To access a member of an object, you begin with the name of the object. This is followed by a dot, and then the identifier of the object. If the member is a method (function) then you will follow the identifier with parentheses. These parentheses may have arguments, if the declaration or definition of the function had parameters.

To solve our problem, we need to assign values to the properties (num1 and num2). This is what the second and third statements in the main function do. An object will not just solve your problem by itself. An object normally has one or more methods that you call to accomplish a particular task, using one or more properties of the object. The add method (function) of our object, does the addition using the two properties of the object; because of the way we defined the method. The fourth statement in the main function calls the add method and assigns the return value to a new int object identified by result. The fifth statement of the main function displays the result.

The Constructor Function
If you want to create an object and at the same time initialize (assign values to) the properties, then you need to define what is called a constructor function as you type the class. After this, to instantiate (create) an object from the class, you must use the constructor function call. The following code illustrates this.

#include <iostream>
using namespace std;

class Calculator
    {
        public:
        int num1;
        int num2;

        Calculator(int ident1, int ident2)
            {
                num1 = ident1;
                num2 = ident2;
            }

        int add ()
            {
                int sum = num1 + num2;
                return sum;
            }
    };


int main()
    {
        Calculator myObject(2,3);
        int result = myObject.add();
        cout << result;

        return 0;
    }

The constructor function is a function (method) declared or defined in the class block. It has no return type. Its name is that of the class. Its purpose is to initialize (assign initial values to) properties. See how the constructor for the calculator class has been defined above.

To instantiate an object from a class that has a constructor function, you must use the constructor function. You begin with the class name; this is followed by a space, then the constructor call with its parentheses and arguments. The first line in the main function illustrates this. Now, the name of the constructor call is the name you want for your object. The arguments in this line are initial values for the properties, num1 and num2. The second statement in the main function calls the add method of the object. The third statement in the main function displays the result. Read and try the above code. You can use this code to add different pairs of numbers; just change the argument of the constructor call.

The Default Constructor
If you do not define a constructor function for your class, C++ provides you with a default constructor unknown to you. The previous code above, is an example with the default constructor. During instantiation with the default constructor the name of the constructor is the name of the new object you want, without parentheses and without arguments. The first line in the main function of the previous code illustrates this.

Whether you are dealing with the default constructor or not, in the class typing, the name of the constructor is the class name; on the other hand, when instantiating an object, the name of the constructor is the name you want for the new object; this name may have parentheses if the class had a constructor function; if the class did not have a constructor function, this name will not have parentheses.

Syntax to access Object Members
Remember, everything being equal, you use objects, not classes. You create an object from a class. A member of an object or class is a property or a method. The syntax to access a member of an object is

    objectName.member

If the member is a method, then you need to follow this up with parentheses. We have not used any method with arguments above, but methods can have arguments; in the typing of the class, the methods would have parameters.

There is more to Classes than I have given. However, I will not go into those extra bits in this basic tutorial series. Let us end here and continue in the next part of the series.

Chrys

Related Courses

C++ Course
Relational Database and Sybase
Windows User Interface
Computer Programmer – A Jack of all Trade – Poem
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message