Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Getting Started With Object Oriented Programming in C++ (http://www.go4expert.com/articles/getting-started-object-oriented-t29957/)

usmanmalik 2Jan2014 20:33

Getting Started With Object Oriented Programming in C++
 
Object oriented programming or commonly known as OOP is an advanced programming concept. OOP principles form the basis of all the modern programming languages of today. When programming languages were at their inception stages, there was no concept of objects and classes and a simple program use to take hundreds of lines of code. Also, such programs were not well organized, reusability of code was minimum and maintainability was also an issue. Such type of programming where you write code without classifying it into classes and object is known as structural or procedural programming and languages which do not support object oriented programming are called procedural languages. C language is the probably the most prominent and successful language that do not support object oriented programming features.

Now, in order to explain what object oriented programming is, let us take the example of an airplane. An airplane has several parts; it has wings, an engine, cockpit, wheels etc. Also, airplane has several attributes associated with it. For example capacity, horse power of engine, length of wings etc. An airplane can also perform several functionalities, an airplane off course flies, lands, take offs, take turns in all directions, opens its wheel before landing etc. Airplane has a pilot that operates the airplane. In order to fly an airplane several components interact together to perform a function. You need wings, you need engine thrust and you need a pilot and so on. Now, consider a scenario where you have to program a flight simulator game and you have to code all the scenarios of flying an airplane. What will you do? Here object oriented programming comes into play

What is Class?



The simplest definition of object oriented programming is the programming paradigm where every piece of code is treated as a part of class. What is class then? Classis basically anything which has some attribute associated with it and can perform certain functions. In the airplane example, airplane can be treated as a class because it has certain attributes and can perform several functions. Attributes of airplane can be price, capacity and name. Similarly the function that airplane can perform is takeoff, land and turn. Similarly, engine is a part of airplane but engine itself can be treated as a class. Engine has horse power as attribute and start/stop as functions. It shows that a class can be composed of further classes and several classes interact together to perform certain functions. A pilot is another example of a class, a pilot has a name, age, salary and so and the function he performs is starting the airplane, move it, etc.

Therefore in short, we can say that anything that has some attributes and perform certain functions is a candidate of being declared as a class.

Syntax

Declaring a class in C++ is a very simple process. A key word class is used followed by the name of the class. This is followed by opening and closing braces. In between the braces, you specify the attributes and functions. An airplane class can be defined as.

Example 1:
Code:

class Airplane
{
private:
        string name;
        int capacity;
        int speed;
public:
        void takeoff()
        {
                cout<<"The takeoff function is called.";
        }

        void land()
        {
                cout<<"The land function is called";
        }

        int showCapacity()
        {
                return capacity;
        }
};

In the above lines of code, we have declared a class Airplane. Inside the class first we have the attributes related to airplane. In this case we have capacity, name and speed of the air plane.

Attributes are followed by the function; we have three functions in this code. Takeoff, Land and showCapacity.

What is an object?



Now we have seen what a class basically is. You must be figuring out what an object is. A class is nothing but a blue print. For example when you write the code in Example1, nothing is allocated in the memory. No space is created in the memory for the variables and functions inside the class. Then how these variables are accessed? The answer is simple, the variables of the class are accessed using objects unless the variables are static which we will see in some of our later tutorials.

Therefore, an object is actual existence of class inside the memory. If you consider class as a blue print of the house, an object can be considered as a house itself. The shape of the house will depend upon the blue print and several houses can be built using one blue print. A class and object have similar relationship as blue print has to house. You can instantiate several objects of the same class.

Syntax

To declare an object, you just have to write the class name followed by object name. Objects can have any name except the keywords.

In Example2, we will instantiate object of Airplane class and then will show you how to access the variables of a class through objects.

Example2:
Code:

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

class  Airplane
{
private:
        string name;
        int capacity;
        int speed;
public:
        void takeoff()
        {
                cout<<"The takeoff function is called.";
        }
        void land()
        {
                cout<<"The land function is called";
        }
        int showCapacity()
        {
                return capacity;
        }
};

int main()
{
        Airplane plane;
        plane.takeoff();
}

Pay attention to the above code. Here we have modified the code in Example1. Note, the body of the class is followed by a semicolon, as in the case of structures. Now come to the main function; inside the main function we have declared an object plane of class Airplane and in the next line we have accessed the takeoff function of the airplane.

You can see that accessing a class member through object is extremely simple. You just have to put a Dot operator ‘. ’ between the object name and the member you want to access. Here we have accessed the takeoff function. You can also access the attributes of the class using the same technique, provided the attributes are defined public. Here in this case, the attributes are defined private hence they cannot be accessed using the ‘.’.

The output of the above code is shown in Output2

http://imgs.g4estatic.com/articles/b...pp/output2.png

An important distinction needs to be made here between the class and structures. In C++ structures all the member variables are public by default whereas in C++ classes all the member variables are private by default and we have to explicitly change access modifier to public which we have done in case of member functions. Member variables are usually kept private and access to member variables is provided through member functions which are public.

What is a Constructor?



In simplest words, constructor can be defined as a member function which instantiate the member at the time when object of a class is created. Often times we want that a class has some predefined values when its object is created. For example we might want that when the object of airplane class is created, the speed, capacity and name variables should possess some predefined values. Constructor allows us to perform this task.

Syntax

Constructor is basically a method whose name is similar to the name of the class and inside the method variables of the class are initialized. Remember, a constructor has not return type, not even void. In Example3, we will assign some values to the speed, capacity and name variables of the class and will then display them.

Example3
Code:

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

class  Airplane
{
private:
        string name;
        int capacity;
        int speed;
public:
        Airplane() // Constructor
        {
                name = "boeng 777";
                capacity =400;
                speed = 600;
        }
        void takeoff()
        {
                cout<<"The takeoff function is called.";
        }

        void land()
        {
                cout<<"The land function is called";
        }
        int showCapacity()
        {
                return capacity;
        }

        int showSpeed()
        {
                return speed;
        }
        string showName()
        {
                return name;
        }
};

int main()
{
        Airplane plane;
        plane.takeoff();
        cout <<"\nThe name of the plane is: "<<plane.showName();
        cout <<"\nPlane has capacity of: "<<plane.showCapacity()<<" people.";
        cout <<"\nThe speed of the plane is: "<<plane.showSpeed() <<" Km/h";
       
}

Usually, the first method of a class is constructor as can be seen in code of Example3. You must be wondering where the call to constructor is. Actually what happens is that when the object of a class is instantiated, the compiler looks for the constructor and automatically calls it, executing the code inside the constructor and values are assigned to the variables. If there are no user defined constructor, the default constructor is called that performs nothing.
In Example three we have assigned some values to the speed, capacity and name variable inside the constructor. Then we have added three functions to the class: showSpeed(), showCapacity() and showName() which return int, int and string respectively. Inside the main function we have called these functions and have displayed the values assigned to these variables.

The output of Example3 will be something like:

http://imgs.g4estatic.com/articles/b...pp/output3.png

Parameterized and overloaded Constructors

In Example3, we take some random values and assigned them to class members inside constructors. But like functions, you can also pass parameter to constructor when the object is defined. Example4 explains how we can pass parameter to the constructor. Also, like overloaded functions we can have overloaded constructor where the constructor that matches the parameters passed in object definition is called. We will explain these concepts in Example4.

Example4
Code:

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

class  Airplane
{
private:
        string name;
        int capacity;
        int speed;
public:
        Airplane() // Constructor
        {
                name = "boeng 777";
                capacity =400;
                speed = 600;
        }
        Airplane(string nm, int spd, int cpcty) // Constructor 2
        {
                name = nm;
                speed = spd;
                capacity=cpcty;
        }
        void takeoff()
        {
                cout<<"The takeoff function is called.";
        }

        void land()
        {
                cout<<"The land function is called";
        }

        int showCapacity()
        {
                return capacity;
        }

        int showSpeed()
        {
                return speed;
        }

        string showName()
        {
                return name;
        }
};

int main()
{
        Airplane plane("Boeng 777",600, 400);
        plane.takeoff();
        cout <<"\nThe name of the plane is: "<<plane.showName();
        cout <<"\nPlane has capacity of: "<<plane.showCapacity()<<" people.";
        cout <<"\nThe speed of the plane is: "<<plane.showSpeed() <<" Km/h"<<endl<<endl;

        cout<<"Plane 2.\n";
        Airplane plane2;
        plane2.takeoff();
        cout <<"\nThe name of the plane is: "<<plane2.showName();
        cout <<"\nPlane has capacity of: "<<plane2.showCapacity()<<" people.";
        cout <<"\nThe speed of the plane is: "<<plane2.showSpeed() <<" Km/h";
}

In Example4, we have defined another constructor inside the class that takes three parameters one of type string and two of type integer. These values are assigned to the Airplane class members name, speed and capacity respectively. Note we haven’t omitted the constructor we wrote in Example3. Now come towards the main function, inside the main function we have defined two objects of Airplane class. Consider the plane object first. While instantiating plane object we passed three parameters of string, int and int type respectively. When control reaches at this point, it will search for any corresponding constructor which accept these values and execute that constructor. We have one constructor which accepts string, int and int respectively.

Now, consider the second object plane2, here we do not passed any values to the object therefore the constructor that will be executed would be the one who doesn’t accept any parameter. The output of the code is as follows.

http://imgs.g4estatic.com/articles/b...pp/output4.png

Destructor



Destructor is opposite of constructor. Destructor is the function that is executed when object is destroyed. Syntax of destructor is similar to constructor. Usually, destructor is used to perform garbage collection or any function that needs to be performed when an object is destroyed.
Code:

~Airplane()
{
        cout<<"Destructor is Called";
}

Note, destructor declaration is similar to the constructor with only difference is that a tilde sign is appended at the beginning of the constructor name.

Object oriented programming is a very vast subject and cannot be covered in a single tutorial. However, in this tutorial I have shown you a glimpse of what object oriented programming basically is. In our future tutorials, we will elaborate more advanced object oriented features such as encapsulation, polymorphism and inheritance. But for that you have to Keep visiting this forum.


All times are GMT +5.5. The time now is 17:26.