0% found this document useful (0 votes)
14 views

Chapter 02 PCPF

Uploaded by

shubham060505
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Chapter 02 PCPF

Uploaded by

shubham060505
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Module II

Imperative Paradigm:
Data Abstraction in Object
Orientation
Grouping of data and Operations- Encapsulation,
Overloading, Polymorphism, Inheritance, Initialization
and Finalization, Dynamic Binding.
Data Abstraction

• 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.
• Real time example:
Driving a car, Television…
• We can implement Abstraction in C++ using classes.
• use access specifiers to enforce restrictions on class members
For example:
• Members declared as public in a class, can be accessed from anywhere in the program.
• Members declared as private in a class, can be accessed only from within the class. They
are not allowed to be accessed from any part of code outside the class. 2
Advantages of Data Abstraction:
• Helps the user to avoid writing the low level code
• Avoids code duplication and increases reusability.
• Can change internal implementation of class independently without
affecting the user.
• Helps to increase security of an application or program as only
important details are provided to the user.

3
Elements of Object Oriented Programming
• Class
• Encapsulation
• Inheritance
• Polymorphism
• Initialization & finalization
• Dynamic Binding
Popular Object-Oriented Programming Languages
• Java, Python, C++, Ruby, C#...
• First object oriented programming language is Simula-67
• Smalltalk 🡪 first pure object oriented programming language

4
Encapsulation
• Encapsulation is defined as the wrapping up of data under a single unit.

• Encapsulation is a process of combining data members and functions in a single unit called class.
• This is to prevent the access to the data directly, the access to them is provided through the
functions of the class.
• It is one of the popular feature of OOP that helps in data hiding.
• In C++ encapsulation can be implemented using Class and access modifier.

5
There are 3 types of access modifiers available in C++:
1. Public 2. Private 3.Protected
Public:
- All the class members declared under the public specifier will be available to everyone.
- The data members and member functions declared as public can be accessed by other classes and
functions too.
- The public members of a class can be accessed from anywhere in the program using the direct member
access operator (.) with the object of that class.
Private:
- The class members declared as private can be accessed only by the member functions inside the class.
- They are not allowed to be accessed directly by any object or function outside the class.
- Only the member functions are allowed to access the private data members of a class.
Protected:
- Protected access modifier is similar to private access modifier in the sense that it can’t be accessed outside
of it’s class unless with the help of friend class, the difference is that the class members declared as Protected
can be accessed by any subclass(derived class) of that class as well.

6
Program- 01 Example of Encapsulation in C++

#include<iostream> int main()


using namespace std; {
class Sum Sum s;
s.add();
{ return 0;
private: int a,b,c; }

public:
Output:
void add()
{ Enter any two numbers: 12
13
cout<<"Enter any two numbers: ";
Sum: 25
cin>>a>>b;
c=a+b;
cout<<"Sum: "<<c;
}
};
7
Program- 02 Encapsulation program with get and set method
#include <iostream> int main() {
using namespace std; Employee myObj;
myObj.setSalary(50000);
class Employee { cout << myObj.getSalary();
private: return 0;
int salary; }

public: output
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};

8
Advantages of Encapsulation:

• Data Hiding: The user will have no idea about the inner implementation of the class. It will not be
visible to the user how the class is storing values in the variables. The user will only know that we
are passing the values to a setter method and variables are getting initialized with that value.

• Increased Flexibility: We can make the variables of the class read-only or write-only depending
on our requirement. If we wish to make the variables read-only then we have to omit the setter
methods like setName(), setAge(), etc. from the above program or if we wish to make the variables
as write-only then we have to omit the get methods like getName(), getAge(), etc. from the above
program

• Reusability: Encapsulation also improves the re-usability and is easy to change with new
requirements.

• Testing code is easy: Encapsulated code is easy to test for unit testing. 9
Encapsulation in Different Imperative Paradigms

• Modules
• Classes
• Nesting(inner class)
• Type Extension
• Extension without inheritance

10
Modules
• Module-based languages with data hiding 🡪 Clu, Modula, Euclid
• In Clu and Euclid, the declaration and definition (header and body) of a module always appear together.
• In Modula-2, programmers have the option of separating the header and body of a module.
• “internal” modules, in which the two parts appear together.
• In an “external” module (meant for separate compilation), the header appears in one source file and the body
in another.
• there is no way to divide the header into public and private parts; everything in it is public (i.e., exported).
• Ada, which also allows the headers and bodies of modules (called packages) to be separated.
package foo is -- header
...
type T is private;
...
private -- definitions below here are inaccessible to users
...
type T is ... -- full definition
... 11
Classes
Visibility rules:
• Other object-oriented languages take different approaches to visibility.
• Eiffel is more flexible than C++
• Derived classes in Eiffel can both restrict and increase the visibility of members of base classes.
• Every method (called a feature in Eiffel) can specify its own export status.
• If the status is {NONE} then the member is effectively private (called secret in Eiffel).
• If the status is {ANY} then the member is effectively public (called generally available in Eiffel)
• Java and C# follow C++ in the declaration of public, protected, and private members
• In Smalltalk and Objective-C, the issue of member visibility never arises: the language allows code
at run time to attempt to make a call to any method name in any object.
• Members of a C# class are private by default

12
Inner class
• Class defined within the outer class
• in C++ and C#, is to allow access to only the static members of the outer class, ,
since these have only a single instance
• Each instance of the inner class must therefore belong to an instance of the outer
class.
• Java classes can also be nested inside methods.
• If a nested class in Java is declared to be static, it behaves as in C++ and C#, with
access to only the static members of the surrounding class.

13
Type Extensions
• Smalltalk, Objective-C, Eiffel, C++, Java, and C# were all support a module
as-type approach to abstraction, in which a single mechanism (the class) provides
both encapsulation and inheritance
• Ada 95, Oberon, CLOS, and Fortran 2003, can be characterized as object-oriented
extensions to languages in which modules already provide encapsulation.
• these languages provide inheritance and dynamic method binding through a
mechanism called extending records.

14
Extending without Inheritance
• The class one wants to extend may not permit inheritance, for instance: in
Java, it may be labeled final; in C#, it may be sealed.
• Even if inheritance is possible in principle, there may be a large body of
existing code that uses the original class name, and it may not be feasible to
go back and change all the variable and parameter declarations to use a new
derived type.
• C# 3.0 provides extension methods, which give the appearance of extending
an existing class:
• An extension method must be static, and must be declared in a static class.
• Its first parameter must be prefixed with the keyword this.

15
Inheritance

• Inheritance is one of the most important feature of Object Oriented Programming.


• Definition:
• The capability of a class to derive properties and characteristics from another
class is called Inheritance.
• Is a process in which one object acquires all the properties and behavior's of its
parent object automatically.
• Sub Class: The class that inherits properties from another class is called Sub class
or Derived Class or Child Class.
Super Class:The class whose properties are inherited by sub class is called Base
Class or Super class or Parent Class.

16
17
Syntax:

class subclass_name : access_mode base_class_name


{
//body of subclass
};
Here, subclass_name is the name of the sub class,
access_mode is the mode in which you want to inherit this sub class for
example: public, private etc.
base_class_name is the name of the base class from which you want to inherit.

18
Program- 03 C++ program to demonstrate implementation of Inheritance

#include<iostream>
using namespace std; {

//Base class Child obj1;


class Parent
{ // An object of class child has all data members
public: // and member functions of class parent
int id_p; obj1.id_c = 7;
};
obj1.id_p = 91;
// Sub class inheriting from Base cout << "Child id is " << obj1.id_c << endl;
Class(Parent) cout << "Parent id is " << obj1.id_p << endl;
class Child : public Parent
{ return 0;
public: }
int id_c;
};
Output
//main function Child id is 7
int main() Parent id is 91

19
Program- 04 // inheritance.cpp
#include <iostream>
using namespace std; int main()
class base //single base class {
{ derive a; //object of derived class
public: a.getdata();
int x; a.readdata();
void getdata() a.product();
{ return 0;
cout << "Enter the value of x = "; cin >> x; } //end of program
}
};
class derive : public base //single derived class
{ Output
private:
int y; Enter the value of x = 3
public: Enter the value of y = 4
void readdata() Product = 12
{
cout << "Enter the value of y = "; cin >> y;
}
void product()
{
cout << "Product = " << x * y;
}
}; 20
Modes of Inheritance
1. Public mode: If we derive a sub class from a public base class. Then the
public member of the base class will become public in the derived class and
protected members of the base class will become protected in derived class.
2. Protected mode: If we derive a sub class from a Protected base class. Then
both public member and protected members of the base class will become
protected in derived class.
3. Private mode: If we derive a sub class from a Private base class. Then both
public member and protected members of the base class will become Private
in derived class.

21
class base
{
public:
int x; class privateDerived: private base
protected: {
int y; // x is private
private: // y is private
int z; // z is not accessible from privateDerived
}; }
class publicDerived: public base
{
// x is public
// y is protected
// z is not accessible from publicDerived
};

class protectedDerived: protected base


{
// x is protected
// y is protected
// z is not accessible from protectedDerived
};
22
Types of Inheritance
Five different types of inheritance:
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)

23
Single inheritance
• In this type of inheritance, one derived class inherits from only one
base class. It is the most simplest form of Inheritance.

24
Multiple Inheritance :
In this type of inheritance a single derived class may inherit from two or more than two base
classes.

25
Program- 05-// multiple inheritance.cpp
class C : public A, public B //C is derived from class A and class B
#include<iostream> {
using namespace std; public:
class A void sum()
{ {
public: cout << "Sum = " << x + y;
int x; }
void getx() };
{
cout << "enter value of x: "; cin >> x; int main()
} {
}; C obj1; //object of derived class C
class B obj1.getx();
{ obj1.gety();
public: obj1.sum();
int y; return 0;
void gety() } //end of program
{ Output
cout << "enter value of y: "; cin >> y; enter value of x: 5
} enter value of y: 4
}; Sum = 9
26
Program- 06 -To find out the student details using multiple inheritance.
#include<iostream>
using namespace std; class statement : public student, public
sports {
class student { int tot, avg;
protected: public:
int rno, m1, m2;
public: void display() {
tot = (m1 + m2 + sm);
void get() { avg = tot / 3;
cout << "Enter the Roll no :"; cout << "\n\n\tRoll No : " <<
cin>>rno; rno << "\n\tTotal : " << tot;
cout << "Enter the two marks :"; cout << "\n\tAverage : " << avg;
cin >> m1>>m2; }
} };
};
int main() {
class sports {
protected: statement obj;
int sm; // sm = Sports mark obj.get();
public: obj.getsm();
obj.display();
void getsm() { return 0;
cout << "\nEnter the sports mark }
:";
cin>>sm;
}
};

27
Hierarchical Inheritance:
In this type of inheritance, multiple derived classes inherits from a single base
class.

28
Program- 07 // hierarchial inheritance.cpp class C : public A //C is also derived from class base
{
#include <iostream> public:
using namespace std; void sum()
{
class A //single base class cout << "\nSum= " << x + y;
{ }
public: };
int x, y; int main()
void getdata() {
{ B obj1; //object of derived class B
cout << "\nEnter value of x and y:\n"; cin >> x >> y; C obj2; //object of derived class C
} obj1.getdata(); Output
}; obj1.product();
class B : public A //B is derived from class base obj2.getdata(); Enter value of x and y:
{ obj2.sum(); 2
public: return 0; 3
void product() } //end of program Product= 6
{ Enter value of x and y:
cout << "\nProduct= " << x * y; 2
} 3
Sum= 5
};
29
Multilevel Inheritance:
In this type of inheritance the derived class inherits from a class, which in turn
inherits from some other class. The Super class for one, is sub class for the other.

30
Program- 08 //Maultilevel inheritance.cpp class derive2 : public derive1 // derived from class derive1
{
#include <iostream> private:
using namespace std; int z;
class base //single base class public:
{ void indata()
public: {
int x; cout << "\nEnter value of z= "; cin >> z;
void getdata() }
{ void product()
cout << "Enter value of x= "; cin >> x; {
} cout << "\nProduct= " << x * y * z;
}; }
class derive1 : public base // derived class from base class }; Output
{ int main()
public: { Enter value of x= 2
int y; derive2 a; //object of derived class
void readdata() a.getdata(); Enter value of y= 3
{ a.readdata();
cout << "\nEnter value of y= "; cin >> y; a.indata(); Enter value of z= 3
} a.product();
}; return 0; Product= 18
} //end of program
31
Hybrid (Virtual) Inheritance :
Hybrid Inheritance is combination of Hierarchical and Multilevel
Inheritance.

32
Polymorphism
- Polymorphism is considered one of the important features of Object-Oriented
Programming.
- Polymorphism allows us to perform a single action in different ways.
- The word “poly” means many and “morphs” means forms, So it means many
forms.
Real life example of polymorphism:
A person at the same time can have different characteristic.
Eg:
Customer, student, passenger, son/daughter
Two types:
• Compile time Polymorphism
• Runtime Polymorphism
33
Compile time polymorphism:
- This type of polymorphism is achieved by function overloading or operator
overloading.
-Static polymorphism/ Early binding/ Static binding
- memory is allocated only at compile time.
Run Time Polymorphism:
- Dynamic Polymorphism/ Late or Lazy Binding/ Dynamic Binding
- memory is allocated only at a run time
- Achieved by Function Overriding or Virtual Functions 34
Compile Time Polymorphism Run time Polymorphism

In Compile time Polymorphism, the call is resolved In Run time Polymorphism, the call is not resolved by the
by the compiler. compiler.

It is also known as Static binding, Early binding and It is also known as Dynamic binding, Late binding and
overloading as well. overriding as well.

It is achieved by method overloading It is achieved by virtual functions and pointers.

It provides fast execution because the method that It provides slow execution as compare to early binding
needs to be executed is known early at the compile because the method that needs to be executed is known at
time. the runtime.

Compile time polymorphism is less flexible as all Run time polymorphism is more flexible as all things
things execute at compile time. execute at run time.

Inheritance is not involved. Inheritance is involved.


35
Function Overloading
• Method/ 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.
• Rules for Function Overloading:
• Overloaded function must have,
• Different type of parameters
• Different number of parameters
• Different sequence of parameters
Example: Int fun(int a);
Not allowed
1. Void print();
2. Void print(int a); Void fun(int a);
3. Void print(float a);
4. Void print(int a, int b);
5. Void print (int a, double b);
6. Void print(double a, int b);
36
The parameters should follow any one or more than one of the following conditions for
Function overloading:
● Parameters should have a different type

add(int a, int b)
add(double a, double b)

● Parameters should have a different number

add(int a, int b)
add(int a, int b, int c)

● Parameters should have a different sequence of parameters.

add(int a, double b)
add(double a, int b)
37
Program- 09
Parameters should have a different type

#include <iostream>
using namespace std;
void add(int a, int b) Output
{
cout << "sum = " << (a + b); sum = 12
} sum = 11.5

void add(double a, double b)


{
cout << endl << "sum = " << (a + b);
}
// Driver code
int main()
{
add(10, 2);
add(5.3, 6.2);

return 0;
}
38
Program- 10
Parameters should have a different number

#include <iostream>
using namespace std;
void add(int a, int b)
{
cout << "sum = " << (a + b);
}
Output
void add(int a, int b, int c)
{ sum = 12
cout << endl << "sum = " << (a + b + c); sum = 15
}
// Driver code
int main()
{
add(10, 2);
add(5, 6, 4);

return 0;
}
39
Program- 11
Parameters should have a different sequence of parameters.
#include<iostream>
using namespace std;
void add(int a, double b)
{
cout<<"sum = "<<(a+b); Output
}
sum = 12.5
void add(double a, int b) sum = 11.5
{
cout<<endl<<"sum = "<<(a+b);
}
// Driver code
int main()
{
add(10,2.5);
add(5.5,6);

return 0;
} 40
Program- 12 C++ program for function overloading
int main() {
#include <iostream>
using namespace std; test obj1;
class test
{ // Which function is called will depend on the parameters passed
public: // The first 'func' is called
obj1.func(7);
// function with 1 int parameter
void func(int x) // The second 'func' is called
{ obj1.func(9.132);
cout << "value of x is " << x << endl;
} // The third 'func' is called
obj1.func(85,64);
// function with same name but 1 double parameter return 0;
void func(double x) }
{
cout << "value of x is " << x << endl;
}
Output:
// function with same name and 2 int parameters
void func(int x, int y) value of x is 7
{ value of x is 9.132
cout << "value of x and y is " << x << ", " << y << endl; value of x and y is 85, 64
}
}; 41
Operator overloading
• Operator overloading is a compile-time polymorphism
• Used to overload or redefines most of the operators
• Used to perform the operation on the user-defined data type
• The advantage of Operators overloading is to perform different
operations on the same operand.
• Operator overloading in c++ is defined as one of the best features that
is used to overload most of the operators like “+” “–” “*” “/” “=” “.”
“,” etc in c++.

42
Operator that cannot be overloaded are as follows:
• Scope operator (::)
• Sizeof
• member selector(.)
• member pointer selector(*)
• ternary operator(?:)

43
Syntax of Operator Overloading

// Normal Function - // Operator Function -

ReturnType operator + (arguments){


ReturnType myFunction (arguments){ // Do something.
// Do something. ................
................ ................
................
// Return something.
................
// Return something. }
................
} // Note that '+' can be replaced by other
// valid operators also like '*', '-', etc.

44
45
● Following is example of operator overloading where we use
aa to call + as operator overloading function and will refer to
argument bb.
● operator overloading function created with type function
with argument and with return type.

46
#include <iostream>
using namespace std; int main()
class Demo{ {
public:
Demo aa,bb,cc;
int a;
void getData(){
cout<<"Enter value of a:"; aa.getData();
cin>>a; bb.getData();
}
void putData(){
cc=aa+bb;
cout<<"value of a:"<<a; cc.putData();
} return 0;
Demo operator+(Demo bb)
{
}
Demo cc;
cc.a=a+bb.a;
return cc;
}
};
47
Program- 13
Function Overriding Example1
#include <iostream>
using namespace std; int main()
class Parent { {
public: Child C;
void Print() C.Print();
{
cout << "Base Function" << endl; return 0;
} }
};
class Child : public Parent {
public:
void Print() Output :
{
cout << "Derived Function" << endl; Derived Function
}
};

48
Program- 14
Function Overriding Example2 (Pig and Dog objects and override the animalSound() method:)
#include <iostream>
#include <string> // Derived class
using namespace std; class Dog : public Animal {
public:
// Base class void animalSound() {
class Animal { cout << "The dog says: bow wow \n";
public: }
void animalSound() { };
cout << "The animal makes a sound \n"; int main() {
} Animal myAnimal;
}; Pig myPig;
Dog myDog;
// Derived class
class Pig : public Animal { myAnimal.animalSound();
public: myPig.animalSound();
void animalSound() { myDog.animalSound();
cout << "The pig says: wee wee \n"; return 0;
} }
};
49
Function Overloading Vs Function Overriding

Function Overloading Function Overriding

It falls under Compile-Time polymorphism It can be both Compile Time or Runtime Polymorphism

A function can be overloaded multiple times as it is resolved at A function cannot be overridden multiple times as it is
Compile time resolved at Run time

Can be executed without inheritance Cannot be executed without inheritance

They are in the same scope They are of different scopes.

50
Dynamic binding:
- The general meaning of binding is linking something to a thing.
- Here linking of objects is done.
- In a programming sense, we can describe binding as linking function definition with the function
call.
- So the term dynamic binding means to select a particular function to run until the runtime. Based
on the type of object, the respective function will be called.
- As dynamic binding provides flexibility, it avoids the problem of static binding as it happened at
compile time and thus linked the function call with the function definition.
- Dynamic binding also helps us to handle different objects using a single function name. It also
reduces the complexity and helps the developer to debug the code and errors.

How to implement dynamic binding?


- virtual functions

51
Virtual functions
• A function declared in the base class and overridden(redefined) in the child class is
called a virtual function.
• The keyword virtual is used to create a virtual function
• When we refer derived class object using a pointer or reference to the base, we can
call a virtual function for that object and execute the derived class's version of the
function.

52
#include <iostream>
using namespace std;
class A {
public:
int main()
{
void final_print() // function that call display
A obj1; // Creating A’s object
{
obj1.final_print(); // Calling final_print
display(); B obj2; // calling b
} obj2.final_print();
virtual void display() // the display function return 0;
{ }
cout<< "Printing from the base class" <<endl;
Output
}
}; Printing from the base class
class B : public A // B inherit a publicly Printing from the derived class
{
public: Hence, dynamic binding links the function call with function
definition with the help of virtual functions.
virtual void display() // B's display
{
cout<< "Printing from the derived class" <<endl;
}
53
};
Static Binding Vs Dynamic Binding

Static Binding Dynamic Binding

It takes place at compile time which is referred to It takes place at runtime so it is


as early binding referred to as late binding

Execution of dynamic binding is


Execution of static binding is faster than dynamic
slower than static binding because
binding because of all the information needed to
the function call is not resolved until
call a function.
runtime.

It takes place using normal function calls,


It takes place using virtual functions
operator overloading, and function overloading.

Real objects never use static binding Real objects use dynamic binding

54
Initialization and Finalization
Constructors are special class functions which performs initialization of every
object.
The Compiler calls the Constructor whenever an object is created.
Constructors initialize values to object members after storage is allocated to
the object.
Destructor on the other hand is used to destroy the class object.

class A
{
public:
int x;
// constructor
A()
{
// object initialization
}
};
55
• Name of constructor will be same as the name of the class, and constructors will never have a
return type.
• Constructors can be defined either inside the class definition or outside class definition using class
name and scope resolution :: operator.
class A
{
public:
int i;
A(); // constructor declared
};
// constructor definition
A::A()
{
i = 1;
}

56
Types of Constructors :
• Constructors are of three types:
1. Default Constructor
2. Parametrized Constructor
3. Copy Constructor

57
Default Constructors:
Default constructor is the constructor which doesn't take any argument. It has no parameter.

class Cube
{
public:
int side;
Cube()
{
side = 10;
}
};

int main()
{
Cube c;
cout << c.side;
}
58
Parameterized Constructors:
These are the constructors with parameter. Using this Constructor you can provide different
values to data members of different objects, by passing the appropriate values as argument.
Copy Constructors
These are special type of Constructors which takes an object as argument, and is used to copy
values of data members of one object into other object.
class Cube
{
public:
int side;
Cube(int x)
{
side=x;
}
};

int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
} 59
Destructors:
- Destructor is a special class function which destroys the object as soon as the scope of
object ends.
- The destructor is called automatically by the compiler when the object goes out of scope.
- Destructors will never have any arguments.
- The syntax for destructor is same as that for the constructor, the class name is used for the
name of destructor, with a tilde ~ sign as prefix to it.
class A
{
public:
// defining destructor for class
~A()
{
// statement
}
};

60
class A
{
int main()
// constructor {
A() A obj1; // Constructor Called
{ int x = 1
if(x)
cout << "Constructor called"; {
} A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
// destructor
~A() Output:
Constructor called
{
Constructor called
cout << "Destructor called"; Destructor called
} Destructor called
};

61

You might also like