Introduction to Object Oriented Programming and Class and Object

Introduction to Object Oriented Programming and Class and Object


Need of Object-oriente programming – 
As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.

Object Oriented Approach
In the object-oriented approach, the focus is on capturing the structure and behavior of information systems into small modules that combines both data and process. The main aim of Object Oriented Design (OOD) is to improve the quality and productivity of system analysis and design by making it more usable.
In analysis phase, OO models are used to fill the gap between problem and solution. It performs well in situation where systems are undergoing continuous design, adaption, and maintenance. It identifies the objects in problem domain, classifying them in terms of data and behavior.
The OO model is beneficial in the following ways −
  • It facilitates changes in the system at low cost.
  • It promotes the reuse of components.
  • It simplifies the problem of integrating components to configure large system.
  • It simplifies the design of distributed systems.

Elements of Object-Oriented System

Let us go through the characteristics of OO System −
  • Objects − An object is something that is exists within problem domain and can be identified by data (attribute) or behavior. All tangible entities (student, patient) and some intangible entities (bank account) are modeled as object.
  • Attributes − They describe information about the object.
  • Behavior − It specifies what the object can do. It defines the operation performed on objects.
  • Class − A class encapsulates the data and its behavior. Objects with similar meaning and purpose grouped together as class.
  • Methods − Methods determine the behavior of a class. They are nothing more than an action that an object can perform.
  • Message − A message is a function or procedure call from one object to another. They are information sent to objects to trigger methods. Essentially, a message is a function or procedure call from one object to another.

Characteristics of an Object Oriented Programming language










Class: The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.
  • A Class is a user-defined data-type which has data members and member functions.
  • Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions define the properties and behaviour of the objects in a Class.
  • In the above example of class Car, the data member will be speed limit, mileage etc and member functions can apply brakes, increase speed etc.
We can say that a Class in C++ is a blue-print representing a group of objects which shares some common properties and behaviours.
Object: An Object is an identifiable entity with some characteristics and behaviour. An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.
class person
{
    char name[20];
    int id;
public:
    void getdetails(){}
};
  
int main()
{
   person p1; // p1 is a object 
}


Object take up space in memory and have an associated address like a record in pascal or structure or union in C.
When a program is executed the objects interact by sending messages to one another.
Each object contains data and code to manipulate the data. Objects can interact without having to know details of each other’s data or code, it is sufficient to know the type of message accepted and type of response returned by the objects.
Encapsulation: In normal terms, Encapsulation is defined as wrapping up of data and information under a single unit. In Object-Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulate them.
Consider a real-life example of encapsulation, in a company, there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keeps records of all the data related to finance. Similarly, the sales section handles all the sales-related activities and keeps records of all the sales. Now there may arise a situation when for some reason an official from the finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of the sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of the sales section and the employees that can manipulate them are wrapped under a single name “sales section”.


Encapsulation in C++
Encapsulation also leads to data abstraction or hiding. As using encapsulation also hides the data. In the above example, the data of any of the section like sales, finance or accounts are hidden from any other section.
Abstraction: Data abstraction is one of the most essential and important features of object-oriented programming in C++. Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of the car or applying brakes will stop the car but he does not know about how on pressing accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.
  • Abstraction using Classes: We can implement Abstraction in C++ using classes. The class helps us to group data members and member functions using available access specifiers. A Class can decide which data member will be visible to the outside world and which is not.
  • Abstraction in Header files: One more type of abstraction in C++ can be header files. For example, consider the pow() method present in math.h header file. Whenever we need to calculate the power of a number, we simply call the function pow() present in the math.h header file and pass the numbers as arguments without knowing the underlying algorithm according to which the function is actually calculating the power of numbers.
Polymorphism: The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.
A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behaviour in different situations. This is called polymorphism.
An operation may exhibit different behaviours in different instances. The behaviour depends upon the types of data used in the operation.
C++ supports operator overloading and function overloading.
  • Operator Overloading: The process of making an operator to exhibit different behaviours in different instances is known as operator overloading.
  • Function Overloading: Function overloading is using a single function name to perform different types of tasks.
    Polymorphism is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some integers, some times there are 2 integers, some times there are 3 integers. We can write the Addition Method with the same name having different parameters, the concerned method will be called according to parameters.








Inheritance: The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.

  • Sub Class: The class that inherits properties from another class is called Sub class or Derived Class.
  • Super Class:The class whose properties are inherited by sub class is called Base Class or Super class.
  • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.








Dynamic Binding: In dynamic binding, the code to be executed in response to function call is decided at runtime. C++ has virtual functions to support this.

Message Passing: Objects communicate with one another by sending and receiving information to each other. A message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. Message passing involves specifying the name of the object, the name of the function and the information to be sent.

Class as a data types

Class: A class in C++ is the building block, that leads to Object-Oriented programming. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some common properties like all of them will have 4 wheelsSpeed LimitMileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.
  • A Class is a user defined data-type which has data members and member functions.
  • Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions defines the properties and behavior of the objects in a Class.
  • In the above example of class Car, the data member will be speed limitmileage etc and member functions can be apply brakesincrease speed etc.
Object as a data types


C++ programs create, destroy, refer to, access, and manipulate objects.
An object, in C++ , is a region of storage that (until C++14) has
  • size (can be determined with sizeof);
  • alignment requirement (can be determined with alignof);
  • storage duration (automatic, static, dynamic, thread-local);
  • lifetime (bounded by storage duration or temporary);
  • type;
  • value (which may be indeterminate, e.g. for default-initialized non-class types);
  • optionally, a name.
The following entities are not objects: value, reference, function, enumerator, type, non-static class member, template, class or function template specialization, namespace, parameter pack, and this.
variable is an object or a reference that is not a non-static data member, that is introduced by a declaration.

Objects are created by definitionsnew-expressionsthrow-expressions, when changing the active member of a union, and where temporary objects are required.











Constructor

A constructor is a member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object(instance of class) create. It is special member function of the class.
How constructors are different from a normal member function?
A constructor is different from normal functions in following ways:



  • Constructor has same name as the class itself
  • Constructors don’t have return type
  • A constructor is automatically called when an object is created.
  • If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body).







Types of Constructors
  1. Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters.
    // Cpp program to illustrate the
    // concept of Constructors
    #include <iostream>
    using namespace std;
      
    class construct {
    public:
        int a, b;
      
        // Default Constructor
        construct()
        {
            a = 10;
            b = 20;
        }
    };
      
    int main()
    {
        // Default constructor called automatically
        // when the object is created
        construct c;
        cout << "a: " << c.a << endl
             << "b: " << c.b;
        return 1;
    }
    Output:
    a: 10
    b: 20
    
    Note: Even if we do not define any constructor explicitly, the compiler will automatically provide a default constructor implicitly.
  2. Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object.
    // CPP program to illustrate
    // parameterized constructors
    #include <iostream>
    using namespace std;
      
    class Point {
    private:
        int x, y;
      
    public:
        // Parameterized Constructor
        Point(int x1, int y1)
        {
            x = x1;
            y = y1;
        }
      
        int getX()
        {
            return x;
        }
        int getY()
        {
            return y;
        }
    };
      
    int main()
    {
        // Constructor called
        Point p1(10, 15);
      
        // Access values assigned by constructor
        cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
      
        return 0;
    }
    Output:
    p1.x = 10, p1.y = 15
    When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly.
     Example e = Example(0, 50); // Explicit call
    
     Example e(0, 50);           // Implicit call
    
    Uses of Parameterized constructor:
    1. It is used to initialize the various data elements of different objects with different values when they are created.
    2. It is used to overload constructors.
    Can we have more than one constructors in a class?
    Yes, It is called Constructor Overloading.
  3. Copy Constructor: A copy constructor is a member function which initializes an object using another object of the same class. Detailed article on Copy Constructor.
Whenever we define one or more non-default constructors( with parameters ) for a class, a default constructor( without parameters ) should also be explicitly defined as the compiler will not provide a default constructor in this case. However, it is not necessary but it’s considered to be the best practice to always define a default constructor.
// Illustration
#include "iostream"
using namespace std;
  
class point {
private:
  double x, y;
  
public:
  // Non-default Constructor & default Constructor
  point (double px, double py) {
    x = px, y = py;
  }
};
  
int main(void) {
  // Define an array of size 10 & of type point
  // This line will cause error
  point a[10];
  
  // Remove above line and program will compile without error
  point b = point(5, 6);
}
Output:
Error: point (double px, double py): expects 2 arguments, 0 provided

Object as a function argument

The objects of a class can be passed as arguments to member functions as well as nonmember functions either by value or by reference. When an object is passed by value, a copy of the actual object is created inside the function. This copy is destroyed when the function terminates. Moreover, any changes made to the copy of the object inside the function are not reflected in the actual object. On the other hand, in pass by reference, only a reference to that object (not the entire object) is passed to the function. Thus, the changes made to the object within the function are also reflected in the actual object.
Whenever an object of a class is passed to a member function of the same class, its data members can be accessed inside the function using the object name and the dot operator. However, the data members of the calling object can be directly accessed inside the function without using the object name and the dot operator.
To understand how objects are passed and accessed within a member function, consider this example.
Example: A program to demonstrate passing objects by value to a member function of the same class

#include<iostream.h>
class weight
{
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
} ;
void weight :: getdata()
{
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
void weight :: putdata ()
{
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
}
void weight :: sum_weight(weight wl,weight w2)
{
gram = wl.gram + w2.gram;
kilogram=gram/1000;
gram=gram%1000;
kilogram+=wl.kilogram+w2.kilogram;
}
int main ()
{
weight wl,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
wl.getdata();
cout<<" \n Enter weight #2" ;
w2.getdata();
w3.sum_weight(wl,w2);
cout<<"/n Weight #1 = ";
wl.putdata();
cout<<"Weight #2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();
return 0;
}

The output of the program is

Enter weight in kilograms and grams
Enter weight #1
Kilograms: 12
Grams: 560
Enter weight #2
Kilograms: 24
Grams: 850
Weight #1 = 12 Kgs. and 560 gms.
Weight #2 = 24 Kgs. and 850 gms.
Total Weight = 37 Kgs. and 410 gms.

In this example, the sum_weight () function has direct access to the data members of calling object (w3 in this case). However, the members of the objects passed as arguments (w1 and w2) can be accessed within function using the object name and dot operator. Note that, the objects w1 and w2 are passed by value, however, they can re passed by reference also. For example, to pass w1 and w2 by reference to the function sum_weight the function will be declared and defined as

void sum_weight (weight &,weight &) ;
void weight :: sum_weight (weight & w1, weight &w2)
{
// body of function

}
Figure shows accessing of member variables inside the sum_weight function;
            

Returning Object as argument

Syntax:
object = return object_name;
Example: In the above example we can see that the add function does not return any value since its return-type is void. In the following program the add function returns an object of type ‘Example'(i.e., class name) whose value is stored in E3.
In this example, we can see both the things that are how we can pass the objects as well as return them. When the object E3 calls the add function it passes the other two objects namely E1 & E2 as arguments. Inside the function, another object is declared which calculates the sum of all the three variables and returns it to E3.
This code and the above code is almost the same, the only difference is that this time the add function returns an object whose value is stored in another object of the same class ‘Example’ E3. Here the value of E1 is displayed by object1, the value of E2 by object2 and value of E3 by object3.
// C++ program to show passing
// of objects to a function
  
#include <bits/stdc++.h>
using namespace std;
  
class Example {
public:
    int a;
  
    // This function will take
    // object as arguments and
    // return object
    Example add(Example Ea, Example Eb)
    {
        Example Ec;
        Ec.a = Ec.a + Ea.a + Eb.a;
  
        // returning the object
        return Ec;
    }
};
int main()
{
    Example E1, E2, E3;
  
    // Values are initialized
    // for both objects
    E1.a = 50;
    E2.a = 100;
    E3.a = 0;
  
    cout << "Initial Values \n";
    cout << "Value of object 1: " << E1.a
         << ", \nobject 2: " << E2.a
         << ", \nobject 3: " << E3.a
         << "\n";
  
    // Passing object as an argument
    // to function add()
    E3 = E3.add(E1, E2);
  
    // Changed values after
    // passing object as an argument
    cout << "New values \n";
    cout << "Value of object 1: " << E1.a
         << ", \nobject 2: " << E2.a
         << ", \nobject 3: " << E3.a
         << "\n";
  
    return 0;
}
Output:
Initial Values 
Value of object 1: 50, 
object 2: 100, 
object 3: 0

New values 
Value of object 1: 50, 
object 2: 100, 
object 3: 200

Thank you,
By Er.Shejwal Shrikant
01-01-2k20



Comments

Popular posts from this blog

NSS CA1 Answers

Database Introduction and Relational Database ppt Notes

BC Mid Sem Ans