Broad Network


OOP Basics in C++

Object Oriented Programming in C++ – Part 1

Forward: In this part of the series, I give you the basic explanation of C++ classes and their objects.

By: Chrysanthus Date Published: 23 Aug 2012

Introduction

This is part 1 of my series, Object Oriented Programming in C++. In this part of the series, we look at C++ OOP basics. OOP stands for Object Oriented Programming. You need basic knowledge in C++ in order to understand this series. If you do not have that knowledge, then read the series in this blog whose first part is titled, Getting Started with C++. To reach the series, type the title and my name Chrys in the Search box of this blog and click Search.

When you have a set of object identifiers and functions that work together and would appear in many parts of your code, you can place 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. The set of object identifiers and functions 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 different in different situations. In order to use the class, you have to create a corresponding different unit from the class, everything being equal. That particular unit created is called an object. Different objects have different values for the identifiers. In this part of the series, I give you the basic explanation of C++ classes and their objects.

You should read this series in the order given; that is you begin with part 1, then part 2, then part 3 and so on.

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 two particular 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 tasks. 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 C++ objects such as fundamental 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 (object identifiers) and methods (functions) of a class are called members of the class. An object created from a class has the same members as the class. A property is also called a data member. A method is also called a member function.

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 and the functions in the class are called methods (we saw this above). Both properties and methods are called members (seen above too). In the description 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 function we now have in the class.

Read through the description of the class above to appreciate how a class is described.

Under normal circumstances, you declare 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 the class (see below).

Note: It is customary to begin the name of a class with a capital letter and the name of an object with a small letter.

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 choose 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 member. 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 (not the name of the constructor function, but note that the name of the constructor function is the name of the class). 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 arguments of the constructor call. A new pair of numbers at instantiation gives you a new different object.

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 becomes 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.

When you are dealing with the constructor function, the name of the constructor in the class description, is the class name; on the other hand, when instantiating an object, the name of the constructor (function) 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 does not have parentheses.

Constructor Function Call at Instantiation without Parentheses
In the constructor code sample above, the constructor function has parameters (arguments). You can have a constructor function without parameters. In that case the values given to the properties will be class default property values. The following code illustrates this:

#include <iostream>
using namespace std;

class Calculator
    {
        public:
        int num1;
        int num2;

        Calculator()
            {
                num1 = 11;
                num2 = 12;
            }

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


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

        return 0;
    }

Read through the code and note that the constructor function does not have parameters. However, in the constructor function definition, the properties have been initialized to 11 and 12. Now that the constructor function does not have parameters, at instantiation (first line of main function above), the constructor function call (myObject) should not have parentheses. However, the constructor function declaration in the class description should have parentheses without parameters (empty parentheses).

A note on instantiated object name: Whether or not you are using the default or non-default constructor function to instantiate (create) an object, the name of the constructor function used in the process, is the name of the new instantiated object. Each instantiated object with a new name is a different created object. You can instantiate many different objects from one class.

Method Definition and Method Calling
In non-OOP C++ programming, you have a function definition (declaration) and the corresponding function calls. The same thing happens with methods in OOP. If the class does not have a constructor (function) definition, C++ provides a default constructor. The constructor is called during instantiation with the name of the new object. In a typical class description, you would find the definition of at least one non-constructor method. A method is called on the instantiated object, with the same name as in the class description.

Defining Method outside Class Description
You can define class methods outside the class description. In such a class description, you will have only method prototypes (declarations).

The following code illustrates this:

#include <iostream>
using namespace std;

class Calculator
    {
        public:
        int num1;
        int num2;

        Calculator()
            {
                num1 = 11;
                num2 = 12;
            }

        int add ();
    };

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


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

        return 0;
    }

Read through the code if you have not done so. A method declaration ending with a semicolon is a method prototype. Note the add() method prototype in the class description. The definition of the add() method is outside the class description. The syntax to defined a method outside the class description is:

    returnValue ClassName::conventionalDefinition

By conventionalDefinition here, you begin with the method declaration without the return value again, and also without the semicolon. See the add() method defined outside, above. Note the use of the scope resolution operator (::).

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 (description), the methods would have parameters. The corresponding calling methods will have parentheses and arguments.

Typing Class Name
It is conventional to type the first letter of a class name in upper case, as in “Calculator”. The object name normally starts with a lower cased letter.

Note: comparing C++ Object Oriented Programming objects and the use of C++ fundamental objects, we see that during declaration (instantiation) of a class object, the role the class name plays, is the same as the role the fundamental object type plays during declaration of the fundamental object.

If you have understood everything so far, then know that there are more exciting things to learn in the next parts of the series. Let us end here and continue in the next part.

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