Object Oriented Programming

Object Oriented programming is a programming style that is associated with the concept of Class, Objects and various other concepts revolving around these two, like Inheritance, Polymorphism, Abstraction, Encapsulation etc.

The classes are the most important feature of C++ that leads to Object Oriented programming. Class is a user defined data type, which holds its own data members and member functions, which can be accessed and used by creating instance of that class.

The variables inside class definition are called as data members and the functions are called member functions.

For example: Class of birds, all birds can fly and they all have wings and beaks. So here flying is a behaviour and wings and beaks are part of their characteristics. And there are many different birds in this class with different names but they all possess this behaviour and characteristics.

Similarly, class is just a blue print, which declares and defines characteristics and behaviour, namely data members and member functions respectively. And all objects of this class will share these characteristics and behaviour.

More about Classes

1.     Class name must start with an uppercase letter (Although this is not mandatory). If class name is made of more than one word, then first letter of each word must be in uppercase. Example,

     class Study, class StudyTonight etc

Classes contain, data members and member functions, and the access of these data members and variable depends on the access specifiers (discussed in next section).

2.     Class's member functions can be defined inside the class definition or outside the class definition.

3.     Class in C++ are similar to structures in C, the only difference being, class defaults to private access control, whereas structure defaults to public.

4.     All the features of OOPS, revolve around classes in C++. Inheritance, Encapsulation, Abstraction etc.

5.     Objects of class holds separate copies of data members. We can create as many objects of a class as we need.

6.     Classes do possess more characteristics, like we can create abstract classes, immutable classes, etc.

Objects

Class is mere a blueprint or a template. No storage is assigned when we define a class. Objects are instances of class, which holds the data variables declared in class and the member functions work on these class objects.

Each object has different data variables. Objects are initialised using special class functions called Constructors. We will study about constructors later.

And whenever the object is out of its scope, another special class member function called Destructor is called, to release the memory reserved by the object. C++ doesn't have Automatic Garbage Collector like in JAVA, in C++ Destructor performs this task.

class Abc

{

 int x;

 void display(){} //empty function

};

 

in main()

{

 Abc obj;   // Object of class Abc created

}

 

 

 

 

Data Encapsulation

Encapsulation Definition:

Encapsulation is a process of capsulation of data and methods into a combined single unit. In C++, encapsulation is used along with the classes concept.

Encapsulation represents the information of variables (attributes) in terms of data and, methods (functions) and its operations in terms of purpose.

·         Encapsulation is the process of combining data and function into a single unit called class.

·         Encapsulation is a powerful feature that leads to information hiding and abstract data type.

·         They encapsulate all the essential properties of the object that are to be created.

·         Using the method of encapsulation the programmer cannot access the class directly.

 

encapsulation and data hiding

Data Hiding Definition:

Data hiding is a technique especially practised in object-oriented programming (OOP).Data hiding is hiding the details of internal data members of an object.

·         Data hiding is also known as Information hiding.

·         Sometimes Data Hiding includes Encapsulation. Thus Data Hiding is heavily related to Abstraction and Encapsulation.

·         Data Hiding is the one most important OOP mechanism. Which is hide the details of the class from outside of the class.

·         The Class used by only a limited set of variables and functions, others are hidden by the class.

Access Specifiers in C++

Access specifiers define how a member's variables and member's functions of a class can be accessed from outside the class. However, all members of a class can be accessed from within the class without any restriction. 

Class members can be declared as public, protected or private access specifiers, which is used to build the encapsulation capabilities of the class.
There are three access specifiers.

Access Specifiers In C++

·         Private members: These can be accessed only from within the members of the same class.

·         Protected members: These can be accessed only from within other members of the same class and its derived classes.

·         Public members: These can be accessed from anywhere where the object is accessible.

By declaring the member variables and functions as a private in a class, the members are hidden from outside the class.Those private members and data cannot be accessed by the object directly.

Encapsulation General Form:

class class_name {
private:
    datatype member_variables;
    datatype member_functions;
public:
    datatype member_variables;
    datatype member_functions;
};
 
main() {
    class_name objectname1, objectname;
}

 

 

 

Encapsulation Example:

class Square {
private:
    int Num;
public:
    void Get()   {
          cout << "Enter Number:";
          cin>>Num;
    }
    void Display()   {
          cout << "Square Is:" << Num*Num;
    }
};
 
void main() {
    Square Obj;
    Obj.Get();
    Obj.Display();
    getch()
}

In the above example, the variable “Num” is private. Hence this variable can be accessed only by the members of the same class and is not accessible anywhere else. Hence outside the classes will be unable to access this variable Which is called data hiding.

At the same time, “Square” class contains two other methods namely “Get” and “Display” which has public members. Here “Get” method just prints the value while “Display” method prints the square of the value in the variable “Num”. Here the class “Square” implements Data Encapsulation concept by capsulation of the value in the variable “Num” and thus allowing the user only to perform a restricted set of operations on the hidden variable “Num”.

Features and Advantages of Data Encapsulation:

·         Encapsulation is used to reduce the complexity and improve reusability.

·         Encapsulation defines the interface clearly which improves the readability and understandability.

·         Encapsulation helps to hide important data and ensures enhanced Security.

·         The member variables and members are bundled into a single unit as a class which makes the maintenance easy.

·         The encapsulated classes are straightforward and are easy to manage and improves the future development of the application.

 

Abstract class

·         A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual function is specified by placing "= 0" in its declaration as follows −

class Box {
·    public:
·       // pure virtual function
·       virtual double getVolume() = 0;
·       
·    private:
·       double length;      // Length of a box
·       double breadth;     // Breadth of a box
·       double height;      // Height of a box
· };

·         The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error.

·         Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error.

·         Classes that can be used to instantiate objects are called concrete classes.

 

Comparison between Abstract Class and Concrete Class:

Abstract Class

Concrete Class

Type

Base class

Default class

Methods

May contain partially implemented methods

All methods are completely implemented

Functions

Some or all declared functions are purely virtual

No purely virtual functions

Instantiation

Cannot be instantiated

Can be instantiated

.

Polymorphism

The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.

C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.

In C++ polymorphism is mainly divided into two types:

§ Compile time Polymorphism

§ Runtime Polymorphism

1.     Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading.

§  Function Overloading: When there are multiple functions with same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of arguments.

// C++ program for function overloading

 

#include <bits/stdc++.h>

using namespace std;

class Geeks

{

    public:

     

    // function with 1 int parameter

    void func(int x)

    {

        cout << "value of x is " << x << endl;

    }

     

    // function with same name but 1 double parameter

    void func(double x)

    {

        cout << "value of x is " << x << endl;

    }

     

    // function with same name and 2 int parameters

    void func(int x, int y)

    {

        cout << "value of x and y is " << x << ", " << y << endl;

    }

};

 

int main() {

     

    Geeks obj1;

     

    // Which function is called will depend on the parameters passed

    // The first 'func' is called

    obj1.func(7);

     

    // The second 'func' is called

    obj1.func(9.132);

     

    // The third 'func' is called

    obj1.func(85,64);

    return 0;

}

Output:

value of x is 7
value of x is 9.132
value of x and y is 85, 64

In the above example, a single function named func acts differently in three different situations which is the property of polymorphism.

Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.

§ Function overriding on the other hand occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.

 

// C++ program for function overriding

 

#include <bits/stdc++.h>

using namespace std;

 

// Base class

class Parent

{

    public:

    void print()

    {

        cout << "The Parent print function was called" << endl;

    }

};

 

// Derived class

class Child : public Parent

{

    public:

     

    // definition of a member function already present in Parent

    void print()

    {

        cout << "The child print function was called" << endl;

    }

     

};

 

//main function

int main()

{

    //object of parent class

    Parent obj1;

     

    //object of child class

    Child obj2 = Child();

     

     

    // obj1 will call the print function in Parent

    obj1.print();

     

    // obj2 will override the print function in Parent

    // and call the print function in Child

    obj2.print();

    return 0;

}

Output:

The Parent print function was called
The child print function was called

Inheritance

https://cdn.programiz.com/sites/tutorial2program/files/cpp-inheritance.jpg

Inheritance is one of the key features of Object-oriented programming in C++. It allows user to create a new class (derived class) from an existing class(base class).

The derived class inherits all the features from the base class and can have additional features of its own.

Why inheritance

Suppose, in your game, you want three characters - a maths teacher, a footballer and a businessman.

Since, all of the characters are persons, they can walk and talk. However, they also have some special skills. A maths teacher can teach maths, a footballer can play football and a businessman can run a business.

You can individually create three classes who can walk, talk and perform their special skill as shown in the figure below.

https://cdn.programiz.com/sites/tutorial2program/files/cpp-without-inheritance_1.jpg

Implementation

class Person 
{
  ... .. ...
};
 
class MathsTeacher : public Person 
{
  ... .. ...
};
 
class Footballer : public Person
{
  .... .. ...
};

In the above example, class Person is a base class and classes MathsTeacher and Footballerare the derived from Person.

#include <iostream>
using namespace std;
 
class Person
{
     public:
        string profession;
        int age;
 
        Person(): profession("unemployed"), age(16) { }
        void display()
        {
             cout << "My profession is: " << profession << endl;
             cout << "My age is: " << age << endl;
             walk();
             talk();
        }
        void walk() { cout << "I can walk." << endl; }
        void talk() { cout << "I can talk." << endl; }
};
 
// MathsTeacher class is derived from base class Person.
class MathsTeacher : public Person
{
    public:
       void teachMaths() { cout << "I can teach Maths." << endl; }
};
 
// Footballer class is derived from base class Person.
class Footballer : public Person
{
    public:
       void playFootball() { cout << "I can play Football." << endl; }
};
 
int main()
{
     MathsTeacher teacher;
     teacher.profession = "Teacher";
     teacher.age = 23;
     teacher.display();
     teacher.teachMaths();
 
     Footballer footballer;
     footballer.profession = "Footballer";
     footballer.age = 19;
     footballer.display();
     footballer.playFootball();
 
     return 0;
}

Output

My profession is: Teacher
My age is: 23
I can walk.
I can talk.
I can teach Maths.
My profession is: Footballer
My age is: 19
I can walk.
I can talk.
I can play Football.

In this program, Person is a base class, while MathsTeacher and Footballer are derived from Person.

Person class has two data members - profession and age. It also has two member functions - walk() and talk().

Both MathsTeacher and Footballer can access all data members and member functions of Person.

However, MathsTeacher and Footballer have their own member functions as well: teachMaths() and playFootball() respectively. These functions are only accessed by their own class.

In the main() function, a new MathsTeacher object teacher is created.

Since, it has access to Person's data members, profession and age of teacher is set. This data is displayed using the display() function defined in the Person class. Also, the teachMaths() function is called, defined in the MathsTeacher class.

Likewise, a new Footballer object footballer is also created. It has access to Person's data members as well, which is displayed by invoking the display() function. The playFootball()function only accessible by the footballer is called then after.

Advantages Of Object Oriented Programming :

Features Of Object Oriented Programming :