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

Data Security Enhancement in Cloud Computing by Proposing a Dke Encryption Protocol

The document outlines a course on Object-Oriented Programming (C++) at the Lebanese French University, covering fundamental concepts such as classes, objects, access specifiers, and various types of constructors and destructors. It explains the methodology of designing programs using classes and objects, highlighting encapsulation, inheritance, and polymorphism. Additionally, it provides syntax examples and practical applications of constructors and destructors in C++.

Uploaded by

cnj59dbpzs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Data Security Enhancement in Cloud Computing by Proposing a Dke Encryption Protocol

The document outlines a course on Object-Oriented Programming (C++) at the Lebanese French University, covering fundamental concepts such as classes, objects, access specifiers, and various types of constructors and destructors. It explains the methodology of designing programs using classes and objects, highlighting encapsulation, inheritance, and polymorphism. Additionally, it provides syntax examples and practical applications of constructors and destructors in C++.

Uploaded by

cnj59dbpzs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Lebanese French University

College of Engineering and Computer Science


Department of Information Technology
Second Semester
2023 - 2024

Asst. Prof. Ashish Sharma


[email protected]

OBJECT-ORIENTED PROGRAMMING (C++)


Lecture – 1-2
Outlines

• Object Oriented Programming

• Object Oriented Programming Concepts

• Class

• Access Specifiers/Modifiers

• Object

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 2


Object Oriented Programming
Object Oriented Programming is a paradigm that provides many concepts, such as
encapsulation, data binding, inheritance, polymorphism etc.
The programming paradigm where everything is represented as an object is known as a
truly object-oriented programming language.
Smalltalk is considered the first truly object-oriented programming language.

Object means a real-world entity such as a pen,


chair, table, etc.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 3


Object Oriented Programming Concepts

Object-Oriented Programming is a methodology or paradigm to design a program using


classes and objects.

It simplifies software development and maintenance by providing some concepts:


1. Class
2. Object
3. Inheritance
4. Polymorphism
5. Data Encapsulation
6. Data Abstraction
7. Message Passing
8. Dynamic Binding

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 4


Class

Facts about Class

1. Class creates by using the keyword class.

2. Class is a user-defined data type.

3. A class declaration defines a new type that links code and


data.

4. Class contains data and functions.

5. Collection of objects is also called class.

6. Class is a logical entity or abstraction.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 5


The general syntax of a class, such as:

class class-name {
private data and functions
access-specifier: //Simple Example of class
data and functions
class Student
access-specifier: {
data and functions
public:
// ... int id; //field or data member
float salary; //field or data member
access-specifier:
data and functions String name;//field or data member
};
} object-list;

Note: The object-list is optional.


Object-Oriented Programming| IT Department| Stage-2 2/1/2024 6
Now, access-specifier is one of these three C++ keywords:
• public
• private
• protected

By default, functions and data declared within a class are private to that class and may be
accessed only by other members of the same class.
The public access specifier allows functions or data to be accessible to other parts of our
program.
The protected access specifier is needed only when inheritance is involved.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 7


Object-Oriented Programming| IT Department| Stage-2 2/1/2024 8
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 9
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 10
Object
Facts about object
1. Object is a real-world entity, for example, a
chair, car, pen, mobile, laptop etc.
2. Object is a variable of type class.
3. Object is an entity that has a state and
behaviour. Here, state means data, and
behaviour means functionality.
4. Object is a runtime entity, and it is created at
runtime and is called an instance of a class.
5. All the members of the class can be accessed Two ways of representing an Object
through object.
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 11
General Syntax of an object, such as:

type_name variable_name ;

where,
type_name is a class_name
variable_name is an object or list of objects

//To create an object of student class using s1 as the reference variable.


Student s1; //creating an object of Student

In this example, Student is the type, and s1 is the reference variable that refers to the instance
of the Student class.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 12


/*Example of class that has two fields: id and name. It creates an instance of the
class, initialises the object and prints the object value.*/
#include <iostream>
using namespace std;
class Student {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
};

int main() Output


{
Student s1; //creating an object of Student 201
s1.id = 201; Ahmed
s1.name = “Ahmed";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 13
/*Example of C++ class where a programmer initializes and displays objects
through a method.*/
#include <iostream>
using namespace std; Output
class Student {
public: 201 Ahmed
int id; //data member (also instance variable) 202 Mohammed
string name; //data member(also instance variable)
void insert(int i, string n)
{ int main(void) {
id = i; Student s1; //creating an object of Student
name = n;
} Student s2; //creating an object of Student
void display() s1.insert(201, “Ahmed");
{ s2.insert(202, “Mohammed");
s1.display( );
cout<<id<<" "<<name<<endl;
s2.display( );
}
}; return 0;
}
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 14
Thanks
Any Question

Object-Oriented Programming| IT Department| Stage-2


?
2/1/2024 15
Lebanese French University

College of Engineering and Computer Science


Department of Information Technology
Second Semester
2023 - 2024

Asst. Prof. Ashish Sharma


[email protected]

OBJECT-ORIENTED PROGRAMMING (C++)


Lecture – 3-4
Outlines

• Constructors for a Class

• Types of Constructor

✓ Default Constructor

✓ Parameterized Constructor

✓ Copy Constructor

• Destructor

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 17


The Class Constructor
A class constructor is a special member function of a class that is executed whenever
programmer create new objects of that class.

A constructor will have exact same name as the class and it does not have any return
type at all, not even void.

Constructors can be very useful for setting initial values for certain member variables.

The Compiler calls the Constructor, whenever an object is created.

Constructors initialize values to object members after storage is allocated to the object.

While defining a constructor you must remember that the name of constructor will be
same as the name of the class, and constructors will never have a return type.
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 18
Constructors can be defined either inside the class definition or outside class definition
using class name and scope resolution operator (::)
Syntax of defining a constructor in the class A by following two ways:
/*
/*
Constructor Definition outside class A
Constructor Definition inside class A
*/
*/
class A
class A
{
{
public:
public:
int i;
int x ;
A( ); // constructor declared
};
// constructor definition
A( )
// constructor definition
{
A :: A( )
// object initialization
{
}
i = 1;
};
}
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 19
Special characteristics of Constructors
1. Constructor should be declared in the public section.

2. Constructor do not have any return type, not even void.

3. Constructor gets automatically invoked, when the objects are created.

4. Constructor cannot be inherited though derived class, programmer can call the base

class constructor.

5. Like other functions, constructor can have default arguments.

6. Programmer cannot refer to their address.

7. Constructors cannot be virtual.


Object-Oriented Programming| IT Department| Stage-2 2/1/2024 20
Types of Constructors in C++
Constructors are of three types:
1. Default Constructor //Example1: Default Constructor
2. Parameterized Constructor class Calc {
int val; //Private data
3. Copy Constructor
public:
Default Constructors in C++
Calc( )
{ Output
Default constructor is the constructor which doesn't take any
val = 20;
argument. It has no parameter, but a programmer can write Error
}
};
some initialization statement there.
int main( )
Syntax: {
class_name (parameter1, parameter2, ...) Calc c1;
{ cout << c1.val;
// constructor Definition }
}
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 21
//Example2: Default Constructor //Example3: Default Constructor
//with public data //with private data
class Cube class Cube
{ {
public: int side; //Private data
int side; //Public data
Cube( ) public:
{ Cube( )
side = 10; {
} side = 10;
}; cout << side;
}
int main( ) };
{
Cube c; Output int main( )
cout << c.side; { Output
} 10 Cube c;
} 10
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 22
Contd…..
In this case, as the object is created the constructor is /*
Example: Default Value by calling
called, which initializes its data members. Default Constructor.
A default constructor is so important for initialization */
class Cube
of object members, that even if programmer do not {
define a constructor explicitly, the compiler will public:
provide a default constructor implicitly.
int side;
};
In this example, default constructor is called by the OUTPUT
compiler to initialize the object data members to int main( )
0 or any random value
{
default value.
Cube c;
This default value will be 0 (Zero) or any random cout << c.side;
integer value. }
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 23
Parameterized Constructors in C++
These are the constructors with parameter. Using this Constructor, programmer can provide
different values to data members of different objects, by passing the appropriate values as
argument. /*Example: Parameterized
Constructors*/ int main( )
class Cube {
By using parameterized constructor,
{ Cube c1(10);
programmer have initialized three (3) public: Cube c2(20);

objects with user defined values. int side; Cube c3(30);


Cube(int x) cout << c1.side;
Programmer can have any number of Output
{ cout << c2.side;
parameters in a constructor. side=x; 10 cout << c3.side;
} 20 }
}; 30

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 24


Copy Constructor in C++
Copy Constructor is a type of constructor which is used to create a copy of an already
existing object of a class type. It is usually of the form X (X&), where X is the class name.
The compiler provides a default Copy Constructor to all the classes.

Syntax of Copy Constructor


Classname(const Classname & objectname)
{
....
}

As it is used to create an object, hence it is called a constructor. And, it creates a new object,
which is exact copy of the existing object, hence it is called copy constructor.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 25


#include<iostream> /* main function */
using namespace std;
class Samplecopyconstructor int main( )
{ {
private:
int x, y; //data members // Normal constructor

public: Samplecopyconstructor obj1(10, 15);


Samplecopyconstructor(int x1, int y1)
{
x = x1; // Copy constructor
y = y1;
} Samplecopyconstructor obj2 = obj1;

/* Copy constructor */
Samplecopyconstructor (const Samplecopyconstructor &sam) cout<<"Normal constructor : ";
{
x = sam.x; obj1.display( );
y = sam.y;
}
cout<<"Copy constructor : ";
void display()
{ obj2.display( );
cout<<x<<" "<<y<<endl; Output
} return 0;
}; Normal constructor : 10 15
} Copy constructor : 10 15
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 26
Destructors in C++
Destructor is used to destroy the class object. Destructor is a special class function, which
destroys the class object, as soon as the scope of object ends.
The destructor is called automatically by the compiler, when the object goes out of scope.

The syntax for destructor is same as that for the class A


{
constructor, the class name is used for the name of
public:
destructor, with a tilde ~ sign as prefix to it.
// defining destructor for class
~A( )
NOTE {
// statement
Destructors will never have any arguments.
}
};

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 27


Example: how Constructor and Destructor are called in C++
Here, programmer have a simple class A with a constructor and destructor. Programmer will
create object of the class and see when a constructor is called and when a destructor gets called.
class A int main( )
{ {
// Constructor A obj1; // Constructor Called
A( ) int x = 1;
{ if(x)
cout << "Constructor called";
{
}
A obj2; // Constructor Called
// Destructor } // Destructor Called for obj2
~A( ) Output } // Destructor called for obj1
{
cout << "Destructor called"; Constructor called
Constructor called
} Destructor called
}; Destructor called
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 28
When an object is created the constructor of that class is called. The object reference is
destroyed when its scope ends, which is generally after the closing curly bracket } for
the code block in which it is created.
The object obj2 is destroyed when the if block ends, because it was created class Dual
{
inside the if block. And the object obj1 is destroyed, when the main() public:
int a;
function ends.
Dual (int x=0)
Single Definition for both Default and Parameterized Constructors {
a = x;
In this example, programmer will use default argument to have a single }
};
definition for both default and parameterized constructor.
int main( )
Here, in this program, a single Constructor definition will take care for both {
Dual obj1;
these object initializations. Programmer does not need for separate default Dual obj2(10);
}
and parameterized constructors.
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 29
Thanks
Any Question

Object-Oriented Programming| IT Department| Stage-2


?
2/1/2024 30
Lebanese French University

College of Engineering and Computer Science


Department of Information Technology
Second Semester
2023 - 2024

Asst. Prof. Ashish Sharma


[email protected]

OBJECT-ORIENTED PROGRAMMING (C++)


Lecture– 5-6
Outlines
• Inheritance in C++

• Visibility of Class Members with Inheritance Concept

• Types of Inheritance

✓ Single Inheritance

✓ Multiple Inheritance

✓ Hierarchical Inheritance

✓ Multilevel Inheritance

✓ Hybrid Inheritance

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 32


Inheritance in C++
Inheritance is the capability of one class object to acquire properties and characteristics
from another class object.

The class whose properties are inherited by other class is called


the Parent or Base or Super class.

And, the class which inherits properties of other class is called Child or Derived or Sub class.
Inheritance makes the code reusable. When a programmer inherits an existing class, all
its methods and fields become available in the new class. Hence, the code is reused.

NOTE: All members of a class except Private, are inherited

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 33


Purpose of Inheritance in C++
1. Code Reusability
2. Method Overriding (Hence, Runtime Polymorphism)
3. Use of Virtual Keyword (A C++ virtual function is a member function in the base class that a programmer
redefine in a derived class. It is declared using the virtual keyword. It tells the compiler to perform dynamic
linkage or late binding on the function.)

Basic Syntax of Inheritance


class Subclass_name : access_mode Superclass_name

While defining a subclass like this, the super class must be already defined or at least declared before the subclass
declaration.
Access Mode may be public, private or protected.
Access Mode is used to specify, the mode in which the properties of superclass will be inherited into subclass.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 34


Example of Inheritance in C++
Whenever a programmer wants to use something from an existing class in a new class, a
programmer can use the concept of Inheritance. Here is a simple example:
class Animal
{
public: int main( ) Animal
int legs = 4;
{ Class Dog inherits
}; properties from its
Dog d; super class Animal
// Dog class inheriting Animal class
cout << d.legs;
class Dog : public Animal Dog
{ cout << d.tail;
public: Output
}
int tail = 1;
}; 41

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 35


Access Modifiers and Inheritance: Visibility of Class Members
It depends on the access modifier used while implementing the inheritance concept to the availability of
the Superclass members in the Subclass. It can either be public, private, or protected.
1. Public Inheritance: This is the most used inheritance mode. In this the protected member of super
class becomes protected members of sub class and public becomes public.
class Subclass : public Superclass
2. Private Inheritance: In private mode, the protected and public members of super class become
private members of derived class.
class Subclass : Superclass // By default its private inheritance
3. Protected Inheritance: In protected mode, the public and protected members of Super class becomes
protected members of Sub class.
class subclass : protected Superclass

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 36


Table showing all the Visibility Modes

Derived Class Derived Class Derived Class


Base class
Public Mode Private Mode Protected Mode
Public Public Private Protected

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 37


Types of Inheritance in C++
In C++, five different types of Inheritance, such as:
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)

1. Single Inheritance in C++


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

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 38


2. Multiple Inheritance in C++
In this type of inheritance, a single derived class may inherit from two
or more than two base classes.

3. Hierarchical Inheritance in C++


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

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 39


4. Multilevel Inheritance in C++
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.

5. Hybrid (Virtual) Inheritance in C++


Hybrid Inheritance is combination of Hierarchical and Multiple Inheritance.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 40


Order of Constructor Call with Inheritance in C++
Base class constructors are always called in the derived class constructors.
Whenever a programmer create derived class object, first the base class default constructor is executed
and then the derived class's constructor finishes execution.

Points to Remember
1. Whether derived class's default constructor is called or parameterized is called, base class's default
constructor is always called inside them.
2. To call base class's parameterized constructor inside derived class's parameterized constructor,
programmer must mention it explicitly (manually) while declaring derived class's parameterized
constructor.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 41


Base class Default Constructor in Derived class Constructors
A default constructor is present in all the classes. In the below example, a programmer will see when and why Base
class and Derived class constructors are called.
class Base class Derived : public Base
{ {
int x; int y;
public: public:
Base( ) // default constructor Derived() // default constructor int main()
{ { {
cout << "Base default constructor\n"; cout << "Derived default constructor\n"; Base b;
} } Derived d1;
};
Derived d2(10);
Derived(int i) // parameterized constructor
}
Output {
Base default constructor cout << "Derived parameterized constructor\n";
Base default constructor }
Derived default constructor };
Base default constructor
Derived parameterized constructor Note: In this example, with both the object creation of the Derived class, Base
class's default constructor is called.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 42


Base class Parameterized Constructor in Derived class Constructor
The programmer can explicitly mention calling the Base class parameterized constructor when the Derived class
parameterized constructor is called.

class Base class Derived : public Base


{ {
int x; int y;

public: public:
Base(int i) // parameterized constructor Derived(int j) : Base(j) // parameterized constructor
{
{
y = j;
x = i;
cout << "Derived Parameterized Constructor\n";
cout << "Base Parameterized Constructor\n";
}
}
};
};
int main()
Output {
Base Parameterized Constructor Derived d(10) ;
Derived Parameterized Constructor }
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 43
Why is Base class Constructor called inside Derived class?
Constructors have a remarkable job of initializing the object correctly. A Derived class constructor has
access only to its class members. However, a Derived class object also has inherited property of the Base
class, and only the base class constructor can properly initialize base class members. Thus all the
constructors are called, and even the base class object would not be well constructed.

Constructor call in Multiple Inheritance in C++


It is almost the same, all the Base class constructors are called inside the derived class
constructor, in the same order in which they are inherited.
class A : public B, public C ;
In this case, a first-class B constructor will be executed, then the class C constructor and then
the class A constructor.
Object-Oriented Programming| IT Department| Stage-2 44
2/1/2024
Hybrid Inheritance and Virtual Class in C++
In Multiple Inheritance, the derived class inherits from more than one base class. Hence, in Multiple
Inheritance, there are a lot of chances of ambiguity.
class A
{ In this case, both class B and C inherits function
class D : public B, public C
void show();
};
{ show() from class A. Hence class D has two
// class definition
}; inherited copies of the function show(). In the
class B : public A
{ main() function when the programmer call function
// class definition
};
int main() show(), then ambiguity arises, because the
{
D obj; compiler doesn’t know which show() function to
class C : public A
obj.show(); call. Hence we use the Virtual keyword while
{
}
// class defintion
};
inheriting the class.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 45


Now by adding a virtual keyword, the programmer instructs the compiler for calling anyone
out of the two show() functions at runtime of the program.

class B : virtual public A


{
class A class D : public B, public C
// class definition
{ {
};
void show( ); // class definition

}; };
class C : virtual public A
{
// class definition
};

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 46


Hybrid Inheritance and Constructor call
As programmers all know that whenever a derived class object is instantiated, the base class constructor is
always called. But in the case of Hybrid Inheritance, as discussed in the above example, if the
programmer creates an instance of class D, then the following constructors will be called:
1. Before class D constructor, constructors of its Superclasses will be called, hence constructors of
class B, class C and class A will be called.
2. When constructors of class B and class C are called, it will again make a call to the Superclass A
constructor.
It will result in multiple calls to the constructor of class A, which is undesirable. As there is a single
instance of a virtual base class shared by multiple classes that inherit from it, the constructor of the base
class is only called once by the constructor of the concrete class, which in this case is class D. All such
calls will be ignored if there is any call for initializing the constructor of class A in class B or class A in
class C while creating an object of class D.
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 47
Thanks
Any Question

Object-Oriented Programming| IT Department| Stage-2


?
2/1/2024 48
Lebanese French University

College of Engineering and Computer Science


Department of Information Technology
Second Semester
2023 - 2024

Asst. Prof. Ashish Sharma


[email protected]

OBJECT-ORIENTED PROGRAMMING (C++)


Lecture– 7-8
Outlines
• Polymorphism in C++

• Types of Polymorphism

• Compile-time Polymorphism

✓ Function Overloading

✓ Operator Overloading

• Runtime Polymorphism

✓ Function Overriding

• Purpose of Polymorphisms

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 50


Polymorphism in C++
The term "Polymorphism" is the combination of "poly" + "morphs" which means many
forms. It is a Greek word.
The word polymorphism means having many forms. Polymorphism is a feature of OOPs that
allows the object to behave differently in different conditions. This allows us to perform a
single action in different ways.

Real life example of polymorphism, 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 behavior in different situations. This is called polymorphism.

Polymorphism is considered as one of the important features of Object Oriented Programming.

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


1. Compile time Polymorphism- This is also known as static (or early) binding.
2. Runtime Polymorphism- This is also known as dynamic (or late) binding.
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 51
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 52
Compile Time Polymorphism in C++
The overloaded functions are invoked by matching the type and number of
arguments.
Therefore, this information is available at the compile time. It means that compiler
selects the appropriate function at the compile time.
Compile Time Polymorphism is achieved by function overloading and operator
overloading and it is also known as static binding or early binding.

Function Overloading in C++


In a C++ program, if multiple functions with same name but different parameters, then these
functions are called overloaded functions.
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 53
Functions can be overloaded by two ways, such as:
1. Change in number of arguments or/and
2. Change in type or datatype of arguments.

Examples of Compile time Polymorphism


In this example, programmer have two functions with same name but different number of
arguments or parameters.
Based on number of parameters, programmer pass during function call and determines which
function is to be called.
So, it is considered as an example of polymorphism because in different conditions the output is
different.
Since, the call is determined during compile time, so it is called compile time polymorphism.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 54


Example: C++ program for function overloading
#include <iostream> int main()
using namespace std; {
class ABC ABC obj1;
{
public: // Which function is called will depend on the parameters
passed
// function with 1 int parameter // The first 'func' is called
void func(int x) obj1.func(7);
{
cout << "value of x is " << x << endl; // The second 'func' is called
} obj1.func(9.132);
Output
// function with same name but 1 double parameter // The third 'func' is called
void func(double x) obj1.func(85,64); value of x is 7
{ return 0; value of x is 9.132
cout << "value of x is " << x << endl; } value of x and y is 85, 64
}

// function with same name and 2 int parameters In this example, a single function named func acts
void func(int x, int y)
{ differently in three different situations, which is the
cout << "value of x and y is " << x << ", " << y << endl;
} property of polymorphism.
};

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 55


Operator Overloading in C++
C++ provides another option to overload operators.
For example, Programmer can make the operator (‘+’) for string class to concatenate two
strings.
Programmer know that this is the addition operator, whose task is to add two operands.
So a single operator ‘+’ when placed between integer operands, adds two integers and when
placed between two string operands, concatenates two strings.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 56


// C++ program to illustrate Operator Overloading in C++
#include<iostream>
using namespace std; int main()
{
class Complex { Complex c1(10, 5), c2(2, 4);
private:
int real, imag; // An example call to "operator+"
public: Complex c3 = c1 + c2;
Complex(int r = 0, int i =0) { c3.print( );
real = r; imag = i; }
} Output
// This is automatically called when '+' is used with
// between two Complex objects 12 + 9i
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real; In this example, the operator ‘+’ is overloaded. The
res.imag = imag + obj.imag;
return res; operator ‘+’ is an addition operator and can add two
}
numbers(integers or floating point), but here the operator
void print() {
cout << real << " + “ << imag << “i" << endl; is made to perform addition of two imaginary or
}
}; complex numbers.
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 57
Run Time Polymorphism in C++
Run time polymorphism is achieved, when the object's method is invoked at the run time
instead of compile time.
It is achieved by method overriding which is also known as dynamic binding or late binding.

NOTE: In function or method overriding, the function in parent class is called the overridden
function and function in child class is called overriding function.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 58


Function Overriding in C++
When child class declares a method, which is already present in the parent class then this is
called function overriding, here child class overrides the parent class members.

In case of function overriding, Programmer have two definitions of the same function, one is in
parent class and another in child class.

The call to the function is determined at runtime to decide, which definition of the function is
to be called, so it is called runtime polymorphism.

Function overriding is a feature that allows the programmer to have a same function in child
class, which is already present in the parent class.

A child class inherits the data members and member functions of parent class, but when
programmer want to override a functionality in the child class, then programmer can use
function overriding. It is like creating a new version of an old function, in the child class.
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 59
Simple Program: Function Overriding in C++
#include <iostream>
using namespace std; int main()
{
class A { //Parent class object
public: A obj;
void disp( ){ obj.disp( );

cout<<"Super Class Function"<<endl; //Child class object


} B obj2;
obj2.disp( );
};
return 0;
class B: public A{
}
public:
void disp( ){
Output
cout<<"Sub Class Function";
} Super Class Function
}; Sub Class Function

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 60


Purpose of Polymorphism in C++
✓Can access different implementations of a function with the same function name.
✓Design and implement systems that are more easily extensible.

For example: function overloading, operator overloading, etc.

For a class, if programmer have: Programmer can have two polymorphisms:


class Shape
ShapePtr->Draw( ) ;
{
public: Compiler implements dynamic binding
void Draw( ) ; Function determined during execution time
//…
ShapeObject.Draw( ) ;
}*ShapePtr, ShapeObject;
Compiler implements static binding
Function determined during compile-time
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 61
Differences between Compile time and Run time Polymorphism

Compile time Polymorphism Run time Polymorphism


The function to be invoked is known at the compile time. The function to be invoked is known at the run time.

It is also known as overloading, early binding and static It is also known as overriding, Dynamic binding and late
binding. binding.

Overloading is a compile time polymorphism where more than Overriding is a run time polymorphism where more than one
one method is having the same name but with the different method is having the same name, number of parameters and
number of parameters or the type of the parameters. the type of the parameters.

It is achieved by function overloading and operator


It is achieved by virtual functions and pointers.
overloading.

It provides fast execution as it is known at the compile time. It provides slow execution as it is known at the run time.

It is less flexible as mainly all the things execute at the


It is more flexible as all the things execute at the run time.
compile time.
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 62
Thanks
Any Question

Object-Oriented Programming| IT Department| Stage-2


?
2/1/2024 63
Lebanese French University

College of Engineering and Computer Science


Department of Information Technology
Second Semester
2023 - 2024

Asst. Prof. Ashish Sharma


[email protected]

OBJECT-ORIENTED PROGRAMMING (C++)


Lecture– 9-10
Outlines
• Implementation of Runtime Polymorphism in C++

✓ Virtual Function

✓ Pure-virtual Function

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 65


virtual Function for inherit in C++
Declaration
Add keyword virtual before function prototype in base class
virtual type func_name(args);
A base-class pointer or reference to a derived class object will call the func_name function.
If a derived class does not define a virtual function, it will automatically inherited from the base class.

Role of virtual functions


• Improve the reuse of the code.

• Provide the uniform interface of the same actions for the sub-classes.

• Eliminate the time consuming and error prone.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 66


Example-1: Function Overriding using virtual function in C++
#include <iostream> Different Case 1:
using namespace std;
void main() Different Case 2:
class B0 {
{ void main()
public: B0 b0, *p;
virtual void display(){ B1 b1;
{
cout<<"B0::display()"<<endl;
D1 d1; B0 b0;
}
}; p=&b0; B1 b1;
class B1: public B0 p->display(); D1 d1;
{ p=&b1; b0.display();
public:
void display(){ p->display(); b1.display();
cout<<"B1::display()"<<endl; p=&d1;
} d1.display();
}; p->display();
}
}
class D1: public B0 Output 1: Output 2:
{
public: B0::display() B0::display()
void display(){
cout<<"D1::display()"<<endl; B1::display( ) B1::display( )
}
}; D1::display() D1::display()

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 67


Continued with Example-1:
If no virtual function definition in derived class D1

With the original main function.

Different Case 2: If a derived class does not define the virtual function, it will
class D1: public B0 use the same definition of the virtual function as the base class.
{
//No Virtual Function definition
Output:
};
B0::display()
B1::display( )
B0::display()

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 68


Example 2: Runtime Polymorphism or Function Overriding using virtual function in C++
#include <iostream>
using namespace std;
//main function
class base
int main()
{
public:
{
virtual void print ( ) { base *bptr;
cout<< "print base class" <<endl; derived d;
} bptr = &d;

void show ( ) { //virtual function,


cout<< "show base class" <<endl;
//binded at runtime
}
};
//(Runtime polymorphism)

class derived : public base bptr->print();


{
public:
// Non-virtual function,
//print () is already virtual function declared in base class, and
//programmer can declare as virtual void print () explicitly
//binded at compile time
void print ( ) {
cout<< "print derived class" <<endl; } bptr->show();
Output:
void show ( ) { return 0; print derived class
cout<< "show derived class" <<endl; } show base class
}
};
Object-Oriented Programming| IT Department| Stage-2 2/1/2024 69
Important Points about virtual Function in C++
1. It cannot be a static member function.

2. Add a keyword virtual before the function prototype, and cannot be used for the definition outside
the class.

3. Can be inherited, all the functions with the same name in the derived class belong to virtual function.

4. Called be the pointer or reference of the base class, and decided by the pointer to the class.

5. Virtual functions can not be defined as friend functions .

6. Virtual functions can not be overloaded, they must be defined as the same declarations as in the base
class with or without virtual.

7. Constructors can not be virtual functions, but destructors can be virtual.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 70


Pure virtual functions and Abstract Class in C++
Abstract classes
• Sole (only) purpose is to provide a base class for other classes
• No objects of an abstract base class can be instantiated
• Too generic to define real objects, can have pointers and references

Concrete classes
Classes that can instantiate objects and provide specifications to make real objects.

Making abstract class


Declare one or more virtual functions as “pure” by initializing the function to zero.
virtual type func_name(args) = 0; //Pure virtual function

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 71


Example: To define Pure virtual Function in C++
class Shape
{
public:
virtual void rotate(int) = 0; // Pure virtual function
virtual void draw( ) = 0; // Pure virtual function
virtual bool is_closed( ) = 0; // Pure virtual function
// ...
};

Shape s; // Error: variable of abstract class Shape

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 72


Program: To implement Pure virtual function in C++

class D1: public B0 void main( )


{ {
#include <iostream> public:
using namespace std; B0 *p;
void display( ) B1 b1;
class B0 D1 d1;
{ {
p = &b1;
public: cout<<"D1::display( ) "<<endl; p -> display();
virtual void display( ) = 0 ; p = &d1;
}; }
p -> display();
};
class B1: public B0 }
{
public:
void display( )
{
cout<<"B1::display( ) "<<endl;
} Output:
}; B1::display( )
D1::display( )

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 73


Differences between Virtual Function and Pure Virtual Function in C++

Virtual Function Pure Virtual Function


Virtual function has their definition in the class. Pure virtual function has no definition.
Declaration:
Declaration:
virtual funct_name(parameter_list)
virtual funct_name(parameter_list) = 0;
{. . . . .};
If a class contains at least one pure virtual
It has no concept of derived class.
function, then it is declared abstract.
In case of pure virtual function derived class
If required, the base class can override a virtual
has to definitely override the pure virtual
function.
function.

Object-Oriented Programming| IT Department| Stage-2 2/1/2024 74


Thanks
Any Question

Object-Oriented Programming| IT Department| Stage-2


?
2/1/2024 75

You might also like