SlideShare a Scribd company logo
18CSC202J
Object Oriented Design and Programming
5/28/2023 1
Prepared by
Department of Data Science and Business
Systems & Networking and
Communications
Session 1
Topic : Types of Constructor
5/28/2023 2
CONSTRUCTORS
• It is very common for some part of an object to require
initialization before it can be used.
• Suppose you are working on 100's of objects and the default
value of a particular data member is needed to be zero.
• Initializing all objects manually will be very tedious job.
• Instead, you can define a constructor function which
initializes that data member to zero. Then all you have to do
is declare object and constructor will initialize object
automatically
5/28/2023 3
CONSTRUCTORS
• 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.
5/28/2023 4
CONSTRUCTORS
• Constructors can be defined either inside the class definition
or outside class definition using class name and scope
resolution :: operator.
5/28/2023 5
CONSTRUCTOR CHARACTERS
• They must be declared in the public scope.
• They are invoked automatically when the objects are
created.
• They do not have return types, not even void and they
cannot return values.
• They cannot be inherited, though a derived class can call the
base class constructor.
• Like other C++ functions, Constructors can have default
arguments.
5/28/2023 6
• Constructors cannot be virtual.
• We can not refer to their addresses.
• An object with a constructor (or destructor) can not be used
as a member of a union.
• They make ‘implicit calls’ to the operators new and delete
when memory allocation is required.
5/28/2023 7
CONSTRUCTOR TYPES
• Constructors are of three types:
– Default Constructor
– Parameterized Constructor
– Copy Constructor
5/28/2023 8
DEFAULT CONSTRUCTOR
• Default constructor is the constructor which doesn't take any
argument. It has no parameter.
– Syntax :
5/28/2023 9
DEFAULT CONSTRUCTOR
– Example
– Output : 10
5/28/2023 10
DEFAULT CONSTRUCTOR
– As soon as the object is created the constructor
is called which initializes its data members.
– A default constructor is so important for
initialization of object members, that even if we
do not define a constructor explicitly, the
compiler will provide a default constructor
implicitly.
5/28/2023 11
DEFAULT CONSTRUCTOR
Output: 0 or any random value
 In this case, default constructor provided by the compiler
will be called which will initialize the object data members
to default value, that will be 0 or any random integer value
in this case.
5/28/2023 12
PARAMETERIZED CONSTRUCTOR
• 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.
5/28/2023 13
PARAMETERIZED CONSTRUCTOR
 OUTPUT
10
20
30
5/28/2023 14
PARAMETERIZED CONSTRUCTOR
 By using parameterized constructor in above case, we
have initialized 3 objects with user defined values. We can
have any number of parameters in a constructor.
5/28/2023 15
COPY CONSTRUCTOR
• 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.
5/28/2023 16
COPY CONSTRUCTOR
• 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.
• 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.
5/28/2023 17
COPY CONSTRUCTOR
• 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 copy, hence it is
called copy constructor.
5/28/2023 18
COPY CONSTRUCTOR
5/28/2023 19
COPY CONSTRUCTOR
 Output :
 Normal constructor : 10 15
 Copy constructor : 10 15
5/28/2023 20
STATIC CONSTRUCTOR
• C++ doesn’t have static constructors but you can emulate them using a
static instance of a nested class.
class has_static_constructor {
friend class constructor;
struct constructor {
constructor() { /* do some constructing here … */ }
};
static constructor cons;
};
// C++ needs to define static members externally.
has_static_constructor::constructor has_static_constructor::cons;
5/28/2023 21
Try out program
5/28/2023 22
Questions
1. What is a copy constructor?
a) A constructor that allows a user to move data from one object to another
b) A constructor to initialize an object with the values of another object
c) A constructor to check the whether to objects are equal or not
d) A constructor to kill other copies of a given object.
2. What happens if a user forgets to define a constructor inside a class?
a) Error occurs
b) Segmentation fault
c) Objects are not created properly
d) Compiler provides a default constructor to avoid faults/errors.
3. How many parameters does a copy constructor require?
a) 1
b) 2
c) 0
d) 3
5/28/2023 23
5/28/2023 24
Session 2 & 3
Feature Polymorphism:
Constructor overloading &
Method overloading
5/28/2023 25
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.
• 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 behaviour in different
situations. This is called polymorphism.
5/28/2023 26
Polymorphism
• Polymorphism is considered as one of the important features
of Object Oriented Programming.
• Polymorphism allows us to perform a single action in different
ways. In other words, polymorphism allows you to define one
interface and have multiple implementations.
• The word “poly” means many and “morphs” means forms, So
it means many forms.
5/28/2023 27
Polymorphism
• Overloading
– Constructor Overloading
– Method Overloading
– Operator Overloading
• Overriding
– Method Overriding
5/28/2023 28
Constructor Overloading
• In C++, We can have more than one constructor in a class with
same name, as long as each has a different list of arguments.
This concept is known as Constructor Overloading
• Overloaded constructors essentially have the same name (name
of the class) and different number of arguments.
• A constructor is called depending upon the number and type of
arguments passed.
• While creating the object, arguments must be passed to let
compiler know, which constructor needs to be called.
5/28/2023 29
Constructor Overloading
• In C++, We can have more than one constructor in a class with same name, as long
as each has a different list of arguments. This concept is known as Constructor
Overloading
• Example
class construct{
public:
float area;
// Constructor with no parameters
construct() {
area = 0;
}
// Constructor with two parameters
construct(int a, int b) {
area = a * b;
}
void disp() {
cout<< area<< endl;
}
};
int main() {
construct o;
construct o2( 10, 20);
o.disp();
o2.disp();
return 1;
}
Output:
0
200
5/28/2023 30
Constructor Overloading
// C++ program to demonstrate constructor overl
oading
#include <iostream>
using namespace std;
class Person { // create person class
private:
int age; // data member
public:
// 1. Constructor with no arguments
Person()
{
age = 20; // when object is created the age will be
20
}
// 2. Constructor with an argument
Person(int a)
{ // when parameterized Constructor is called with
a value the age passed will be initialized
age = a;
}
Int getAge()
{ // getter to return the age
return age;
}
};
int main()
{
Person person1, person2(45);
// called the object of person class in differnt
way
cout<< "Person1 Age = " << person1.getAge()
<<endl;
cout<< "Person2 Age = " << person2.getAge(
) <<endl;
return 0;
}
5/28/2023 31
MCQ Questions
1. Which among the following best describes constructor overloading?
a) Defining one constructor in each class of a program
b) Defining more than one constructor in single class
c) Defining more than one constructor in single class with different
signature
d) Defining destructor with each constructor
Answer: c
Explanation: If more than one constructors are defined in a class with same
signature, then that results in error. The signatures must be different. So that
the constructors can be differentiated.
5/28/2023 32
MCQ Questions
2. Can constructors be overloaded in derived class?
a) Yes, always
b) Yes, if derived class has no constructor
c) No, programmer can’t do it
d) No, never
Answer: d
Explanation: The constructor must be having the same name as that of a
class. Hence a constructor of one class can’t even be defined in another class.
Since the constructors can’t be defined in derived class, it can’t be
overloaded too, in derived class.
5/28/2023 33
MCQ Questions
3. Does constructor overloading include different return types for
constructors to be overloaded?
a) Yes, if return types are different, signature becomes different
b) Yes, because return types can differentiate two functions
c) No, return type can’t differentiate two functions
d) No, constructors doesn’t have any return type
Answer: d
Explanation: The constructors doesn’t have any return type. When we can’t
have return type of a constructor, overloading based on the return type is
not possible. Hence only parameters can be different.
5/28/2023 34
MCQ Questions
4. Why do we use constructor overloading?
a) To use different types of constructors
b) Because it’s a feature provided
c) To initialize the object in different ways
d) To differentiate one constructor from another
Answer: c
Explanation: The constructors are overloaded to initialize the objects of a
class in different ways. This allows us to initialize the object with either
default values or used given values. If data members are not initialized then
program may give unexpected results.
5/28/2023 35
MCQ Questions
5. Which constructor will be called from the object created in the code
below?
class A
{ int i;
A()
{
i=0; cout&lt;&lt;i;
}
A(int x=0)
{
i=x; cout&lt;&lt;I;
}
};
A obj1;
a) Default constructor
b) Parameterized constructor
c) Compile time error
d) Run time error
ANSWER : C
Explanation: When a default constructor is
defined and another constructor with 1 default
value argument is defined, creating object without
parameter will create ambiguity for the compiler.
The compiler won’t be able to decide which
constructor should be called, hence compile time
error.
Method Overloading
• Method overloading is a feature in C++ that allows creation
of several methods with the same name but with different
parameters.
• For example, print(), print(int), and print("Hello") are
overloaded methods.
• While calling print() , no arguments are passed to the
function
• When calling print(int) and print("Hello") , an integer and a
string arguments are passed to the called function.
• Allows one function to perform different tasks
5/28/2023 36
Types of Polymorphism
• Basically, there are two types of polymorphism:
– Compile time (or static) polymorphism
– Run-time (or dynamic) polymorphism.
• Static polymorphism -> Method overloading - calls a function
using the best match technique or overload resolution.
5/28/2023 37
Matching Function Calls With Overloaded Methods
• When an overloaded function is called, one of the
following cases occurs:
• Case 1: A direct match is found, and there is no confusion
in calling the appropriate overloaded function.
• Case 2: If a match is not found, a linker error will be
generated. However, if a direct match is not found, then,
at first, the compiler will try to find a match through the
type conversion or type casting.
• Case 3: If an ambiguous match is found, that is, when the
arguments match more than one overloaded function, a
compiler error will be generated. This usually happens
because all standard conversions are treated equal.
5/28/2023 38
Try out Program
5/28/2023 39
Questions
1. Which of the following permits function overloading on c++?
a) type
b) number of arguments
c) type & number of arguments
d) number of objects
2. Overloaded functions are ________________
a) Very long functions that can hardly run
b) One function containing another one or more functions inside it
c) Two or more functions with the same name but different number of
parameters or type
d) Very long functions
3. What should be passed in parameters when function does not require any
parameters?
a) void
b) blank space
c) both void & blank space
d) tab space
5/28/2023 40
Session 6, 7 & 8
Operator Overloading &
Types
5/28/2023 41
• The utility of operators such as +, =, *, /, >, <, and so on
is predefined in any programming language.
• Programmers can use them directly on built-in data types
to write their programs.
• However, these operators do not work for user-defined
types such as objects.
• Therefore, C++ allows programmers to redefine the
meaning of operators when they operate on class objects.
This feature is called operator overloading
5/28/2023 42
Operator Overloading:
Operator – It is a symbol that indicates an operation.
Arithmetic operators are + (add two numbers), - (subtract two
numbers), * ( Multiply two numbers), / ( Divide between two
numbers).
At now, we will take an Addition ‘+’ Sign, its use of
‘+’ sign is
5+5=10
2.5+2.5=5
5/28/2023 43
❖ Operator Overloading means multiple functions or multiple
jobs. In operator overloading the ‘+’ sign use to add the two
objects.
❖ One of C++’s great features is its extensibility, Operator
Overloading is major functionality related to extensibility.
❖ In C++, most of operators can be overloaded so that they can
perform special operations relative to the classes you create.
5/28/2023 44
❖ For Example, ‘+’ operator can be overloaded to perform an
operation of string concatenation along with its pre-defined
job of adding two numeric values.
❖ When an operator is overloaded, none of its original meaning
will be lost.
❖ After overloading the appropriate operators, you can use
C++’s built in data types.
5/28/2023 45
Unary Operator
- Operators attached to a single operand.
(-a, +a, --a, ++a, a--, a++)
Binary Operator
- Operators attached to two operand.
(a-b, a+b, a*b, a/b, a%b, a>b, a<b )
5/28/2023 46
return-type class-name:: operator op(arg-list)
{
function body
}
EXPLANATION
❖ return type – It is the type of value returned by the specified
operation.
❖ op - It is the operator being overloaded. It may be unary or
binary operator. It is preceded by the keyword operator.
❖ operator op - It is the function
name, Where operator is a keyword.
5/28/2023 47
Introduction
One of the exciting features of C++
Works only on the single variable
It can be overloaded two ways
1. Static member function
2. Friend function
-,+,++,-- those are unary operator which we can
overloaded.
5/28/2023 48
Using a member function to Overload Unary
Operator
5/28/2023 49
Example Program:
Write a program which will convert an positive values in an object to negative
value.
Code:
#include <iostream.h>
class demo
{
int x,y,z;
public:
void getdata (int a, int b,int c)
{
x=a;
y=b;
z=c;
}
Contd...,
5/28/2023 50
void display();
void operator –();
};
void demo::display()
{
cout<<“x=“<<x<<“ny=“<<y<<“nz=“<<z<<endl;
}
void demo::operator –()
{
x=-x;
y=-y;
z=-z;
}
int main()
{
demo obj1;
CONTD...,
5/28/2023 51
obj1.getdata(10,20,30);
obj1.display();
-obj1;
obj1.display();
return 0;
}
Output:
x=10
y=20
z=30
x=-10
y=-20
z=-30
5/28/2023 52
5/28/2023 53
INTRODUCTION
In Binary operator overloading function, there should be one
argument to be passed.
It is overloading of an operator operating on two operands.
5/28/2023 54
#include<iostream> class
multiply
{
int first,second;
public:
void getdata(int a,int b)
{
first=a; second=b;
} Contd...,
5/28/2023 55
void display()
{
cout<<“first=“<<first<<“second=“<<secon<<endl;
}
multiply operator *(multiply c);
};
void multiply::operator *(multiply c)
{
multiply temp;
temp.first=first*c.first;
temp.second=second*c.second;
return temp;
}
Contd..,
5/28/2023 56
int main()
{
multiply obj1,obj2,obj3;
obj1.getdata(15,20);
obj2.getdata(3,45);
obj3=obj1*obj2;
obj3.display();
return 0;
}
Output:
45
900
5/28/2023 57
5/28/2023 58
MCQ Questions
I. In case of operator overloading, operator function must be ______ .
1. Static member functions
2. Non- static member functions
3. Friend Functions
a. Only 2
b. Only 1, 3
c. Only 2 , 3
d. All 1 , 2, 3
5/28/2023 59
MCQ Questions
In case of operator overloading, operator function must be ______ .
1. Static member functions
2. Non- static member functions
3. Friend Functions
a. Only 2
b. Only 1, 3
c. Only 2 , 3
d. All 1 , 2, 3
5/28/2023 60
MCQ Questions
II. Using friend operator function, following perfect set of operators may
not be overloaded.
a. = , ( ) , [ ] , ->
b. <<, = = , [ ] , >>
c. ?, = , ( ) , ++
d. +,-,--,++
5/28/2023 61
MCQ Questions
II. Using friend operator function, following perfect set of operators may
not be overloaded.
a. = , ( ) , [ ] , ->
b. <<, = = , [ ] , >>
c. ?, = , ( ) , ++
d. +,-,--,++
5/28/2023 62
MCQ Questions
III. When overloading unary operators using Friend function,it
requires_____ argument/s.
a. Zero
b. One
c. Two
d. None of these.
5/28/2023 63
MCQ Questions
III. When overloading unary operators using Friend function,it
requires_____ argument/s.
a. Zero
b. One
c. Two
d. None of these.
5/28/2023 64
MCQ Questions
IV. In case of binary operator overloading with member function,
which of following statement should be taken into consideration?
a. Right hand operand must be object.
b. Left hand operand must be object.
c. Both the operands must be objects.
d. All of these should be considered.
5/28/2023 65
MCQ Questions
IV. In case of binary operator overloading with member function,
which of following statement should be taken into consideration?
a. Right hand operand must be object.
b. Left hand operand must be object.
c. Both the operands must be objects.
d. All of these should be considered.
5/28/2023 66
MCQ Questions
V.Which is the correct statement anout operator overloading
in C++?
A. Only arithmetic operators can be overloaded
B. Only non-arithmetic operators can be overloaded
C. Precedence of operators are changed after overlaoding
D. Associativity and precedence of operators does not
change
5/28/2023 67
MCQ Questions
V. Which is the correct statement anout operator overloading
in C++?
A. Only arithmetic operators can be overloaded
B. Only non-arithmetic operators can be overloaded
C. Precedence of operators are changed after overlaoding
D. Associativity and precedence of operators does not
change
Session 11
UML Sequence Diagram
5/28/2023 68
Interaction Diagram
• Interaction diagrams are used to observe the dynamic
behavior of a system.
• Interaction diagram visualizes the communication and
sequence of message passing in the system.
• Interaction diagram represents the structural aspects of
various objects in the system.
• Interaction diagram represents the ordered sequence of
interactions within a system.
• Interaction diagram provides the means of visualizing the
real time data via UML.
5/28/2023 69
• This interactive behavior is represented in UML by two
diagrams known as
– Sequence diagram
– Collaboration diagram.
• Sequence diagram emphasizes on time sequence of
messages from one object to another.
• Collaboration diagram emphasizes on the structural
organization of the objects that send and receive messages.
5/28/2023 70
How to Draw an Interaction Diagram?
• The purpose of interaction diagrams is to capture the dynamic aspect of
a system.
• So to capture the dynamic aspect, we need to understand what a
dynamic aspect is and how it is visualized. Dynamic aspect can be
defined as the snapshot of the running system at a particular moment.
• Following things are to be identified clearly before drawing the
interaction diagram
– Objects taking part in the interaction.
– Message flows among the objects.
– The sequence in which the messages are flowing.
– Object organization.
5/28/2023 71
Sequence Diagram
• A sequence diagram simply depicts interaction between
objects in a sequential order i.e. the order in which these
interactions take place.
5/28/2023 72
Sequence Diagram Notations
Actors :
An actor in a UML diagram represents a type of role where it interacts
with the system and its objects.
5/28/2023 73
2.Lifelines :
 A lifeline is a named element which depicts an individual participant
in a sequence diagram. So basically each instance in a sequence
diagram is represented by a lifeline.
 Lifeline elements are located at the top in a sequence diagram.
 lifeline follows the following format :
Instance Name : Class Name
5/28/2023 74
3.Messages :
 Communication between objects is depicted using messages. The
messages appear in a sequential order on the lifeline.
 We represent messages using arrows. Lifelines and messages form the
core of a sequence diagram.
5/28/2023 75
Synchronous messages
 A synchronous message waits for a reply before the interaction can move
forward.
 The sender waits until the receiver has completed the processing of the
message.
 The caller continues only when it knows that the receiver has processed
the previous message i.e. it receives a reply message.
 A large number of calls in object oriented programming are
synchronous. We use a solid arrow head to represent a synchronous
message.
5/28/2023 76
Asynchronous Messages
 An asynchronous message does not wait for a reply from the receiver.
 The interaction moves forward irrespective of the receiver processing
the previous message or not.
 We use a lined arrow head to represent an asynchronous message.
5/28/2023 77
Create message
 We use a Create message to instantiate a new object in the sequence
diagram.
 It is represented with a dotted arrow and create word labeled on it to
specify that it is the create Message symbol.
For example :
 The creation of a new order on a e-commerce website would require
a new object of Order class to be created.
5/28/2023 78
Delete Message
• We use a Delete Message to delete an object.
• It destroys the occurrence of the object in the system.
• It is represented by an arrow terminating with a x.
For example – In the scenario below when the order is received by the
user, the object of order class can be destroyed
5/28/2023 79
Self Message
• A message an object sends to itself, usually shown as a U
shaped arrow pointing back to itself.
5/28/2023 80
Reply Message
• Reply messages are used to show the message being sent from the
receiver to the sender.
• We represent a return/reply message using an open arrowhead with a
dotted line.
• The interaction moves forward only when a reply message is sent by the
receiver.
5/28/2023 81
Found Message
• A Found message is used to represent a scenario where an unknown
source sends the message.
• It is represented using an arrow directed towards a lifeline from an end
point.
5/28/2023 82
Lost Message
• A Lost message is used to represent a scenario where the recipient is
not known to the system.
• It is represented using an arrow directed towards an end point from a
lifeline.
For example:
5/28/2023 83
Example – Sequence Diagram
5/28/2023 84
Questions
1. What does a message mean?
a) It Passes all communications from one object to another and are
represented by message arrows in sequence diagrams.
b) The message goes from the sending object’s lifeline to the receiving
object’s lifeline.
c) It is a rectangle containing an identifier with a dashed line extending
below the rectangle.
d) List of all attributes.
2. What is a lifeline?
a) It is a frame consisting of a rectangle with a pentagon in its upper left-
hand corner
b) It is a rectangle containing an identifier with a dashed line extending
below the rectangle
c) It is a name compartment; the interaction is represented inside the
rectangle
d) Emergency situation in real world approach.
5/28/2023 85
Session 12
UML Collaboration
Diagram
5/28/2023 86
COLLABORATION DIAGRAM depicts the relationships
and interactions among software objects. They are
used to understand the object architecture within a
system rather than the flow of a message as in a
sequence diagram. They are also known as
“Communication Diagrams.”
In the collaboration diagram, the method call
sequence is indicated by some numbering technique.
The number indicates how the methods are called
one after another.
Collaboration diagram
5/28/2023 87
It is also called as a communication diagram.
It emphasizes the structural aspects of an interaction diagram - how
lifeline connects.
Its syntax is similar to that of sequence diagram except that lifeline
don't have tails.
Messages passed over sequencing is indicated by numbering each
message hierarchically.
Compared to the sequence diagram communication diagram is
semantically weak.
Object diagrams are special case of communication diagram.
It allows you to focus on the elements rather than focusing on the
message flow as described in the sequence diagram.
Sequence diagrams can be easily converted into a collaboration
diagram as collaboration diagrams are not very expressive.
Benefits of Collaboration Diagram
5/28/2023 88
Example
5/28/2023 89
Following diagram represents the sequencing over student management system:
The above collaboration diagram represents a student information
management system. The flow of communication in the above diagram
is given by,
A student requests a login through the login system.
An authentication mechanism of software checks the request.
If a student entry exists in the database, then the access is allowed;
otherwise, an error is returned.
Example
5/28/2023 90
1. A collaboration diagram shows
a. Structural Aspect
b. Behavioral Aspect
c. Environmental Aspect
d. Both A and B
e. Both B and C
2. which diagram is used to show interactions between messages
are classified as?
a.activity
b.state chart
c.collaboration
d.object lifeline
MCQ’s
5/28/2023 91
Session 13
Inheritance & Types
5/28/2023 92
Inheritance
Inheritance is the capability of one class to acquire properties
and characteristics from another class. 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.
Definition
01
Type
s
0
3
Single Inheritance, Multiple Inheritance, Hierarchical
Inheritance, Multilevel Inheritance, and Hybrid Inheritance (also
known as Virtual Inheritance)
Note : All members of a class except Private, are inherited
1. Code Reusability
2. Method Overriding (Hence, Runtime Polymorphism.)
3. Use of Virtual Keyword
Advantages
04
Synta
x
02
Inheritance Types
Single
01 Multiple
02 Hierarchic
al
03
Multilevel
04
Hybrid
05
Modes of
Inheritance
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
Public
01
private
03
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.
The private members in the base class cannot be directly
accessed in the derived class, while protected members can
be directly accessed.
Note:
Protected
02
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.
Inheritance Access Matrix
5/28/2023 97
Ad

More Related Content

Similar to Unit 2 Methods and Polymorphism-Object oriented programming (20)

Constructors & Destructors
Constructors  & DestructorsConstructors  & Destructors
Constructors & Destructors
Rokonuzzaman Rony
 
C questions
C questionsC questions
C questions
parm112
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
rashmita_mishra
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
Saharsh Anand
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objects
Prem Kumar Badri
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Sunipa Bera
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
Karthik Sekar
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
Prem Kumar Badri
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
Ali Aminian
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
Rassjb
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
Kaushik Raghupathi
 
5 Constructors and Destructors
5 Constructors and Destructors5 Constructors and Destructors
5 Constructors and Destructors
Praveen M Jigajinni
 
constructor in object oriented program.pptx
constructor in object oriented program.pptxconstructor in object oriented program.pptx
constructor in object oriented program.pptx
urvashipundir04
 
Constructor and Destructor in c++
Constructor  and Destructor in c++Constructor  and Destructor in c++
Constructor and Destructor in c++
aleenaguen
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
Lovely Professional University
 
Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2
Lovely Professional University
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
murugeswariSenthilku
 
constructocvbcvbcvbcvbr-Destructor (1).pptx
constructocvbcvbcvbcvbr-Destructor (1).pptxconstructocvbcvbcvbcvbr-Destructor (1).pptx
constructocvbcvbcvbcvbr-Destructor (1).pptx
WrushabhShirsat3
 
C questions
C questionsC questions
C questions
parm112
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
rashmita_mishra
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
Saharsh Anand
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objects
Prem Kumar Badri
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Sunipa Bera
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
Karthik Sekar
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
Ali Aminian
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
Rassjb
 
constructor in object oriented program.pptx
constructor in object oriented program.pptxconstructor in object oriented program.pptx
constructor in object oriented program.pptx
urvashipundir04
 
Constructor and Destructor in c++
Constructor  and Destructor in c++Constructor  and Destructor in c++
Constructor and Destructor in c++
aleenaguen
 
constructocvbcvbcvbcvbr-Destructor (1).pptx
constructocvbcvbcvbcvbr-Destructor (1).pptxconstructocvbcvbcvbcvbr-Destructor (1).pptx
constructocvbcvbcvbcvbr-Destructor (1).pptx
WrushabhShirsat3
 

Recently uploaded (20)

How to use nRF24L01 module with Arduino
How to use nRF24L01 module with ArduinoHow to use nRF24L01 module with Arduino
How to use nRF24L01 module with Arduino
CircuitDigest
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Data Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptxData Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptx
RushaliDeshmukh2
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
How to use nRF24L01 module with Arduino
How to use nRF24L01 module with ArduinoHow to use nRF24L01 module with Arduino
How to use nRF24L01 module with Arduino
CircuitDigest
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Data Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptxData Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptx
RushaliDeshmukh2
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Ad

Unit 2 Methods and Polymorphism-Object oriented programming

  • 1. 18CSC202J Object Oriented Design and Programming 5/28/2023 1 Prepared by Department of Data Science and Business Systems & Networking and Communications
  • 2. Session 1 Topic : Types of Constructor 5/28/2023 2
  • 3. CONSTRUCTORS • It is very common for some part of an object to require initialization before it can be used. • Suppose you are working on 100's of objects and the default value of a particular data member is needed to be zero. • Initializing all objects manually will be very tedious job. • Instead, you can define a constructor function which initializes that data member to zero. Then all you have to do is declare object and constructor will initialize object automatically 5/28/2023 3
  • 4. CONSTRUCTORS • 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. 5/28/2023 4
  • 5. CONSTRUCTORS • Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution :: operator. 5/28/2023 5
  • 6. CONSTRUCTOR CHARACTERS • They must be declared in the public scope. • They are invoked automatically when the objects are created. • They do not have return types, not even void and they cannot return values. • They cannot be inherited, though a derived class can call the base class constructor. • Like other C++ functions, Constructors can have default arguments. 5/28/2023 6
  • 7. • Constructors cannot be virtual. • We can not refer to their addresses. • An object with a constructor (or destructor) can not be used as a member of a union. • They make ‘implicit calls’ to the operators new and delete when memory allocation is required. 5/28/2023 7
  • 8. CONSTRUCTOR TYPES • Constructors are of three types: – Default Constructor – Parameterized Constructor – Copy Constructor 5/28/2023 8
  • 9. DEFAULT CONSTRUCTOR • Default constructor is the constructor which doesn't take any argument. It has no parameter. – Syntax : 5/28/2023 9
  • 10. DEFAULT CONSTRUCTOR – Example – Output : 10 5/28/2023 10
  • 11. DEFAULT CONSTRUCTOR – As soon as the object is created the constructor is called which initializes its data members. – A default constructor is so important for initialization of object members, that even if we do not define a constructor explicitly, the compiler will provide a default constructor implicitly. 5/28/2023 11
  • 12. DEFAULT CONSTRUCTOR Output: 0 or any random value  In this case, default constructor provided by the compiler will be called which will initialize the object data members to default value, that will be 0 or any random integer value in this case. 5/28/2023 12
  • 13. PARAMETERIZED CONSTRUCTOR • 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. 5/28/2023 13
  • 15. PARAMETERIZED CONSTRUCTOR  By using parameterized constructor in above case, we have initialized 3 objects with user defined values. We can have any number of parameters in a constructor. 5/28/2023 15
  • 16. COPY CONSTRUCTOR • 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. 5/28/2023 16
  • 17. COPY CONSTRUCTOR • 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. • 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. 5/28/2023 17
  • 18. COPY CONSTRUCTOR • 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 copy, hence it is called copy constructor. 5/28/2023 18
  • 20. COPY CONSTRUCTOR  Output :  Normal constructor : 10 15  Copy constructor : 10 15 5/28/2023 20
  • 21. STATIC CONSTRUCTOR • C++ doesn’t have static constructors but you can emulate them using a static instance of a nested class. class has_static_constructor { friend class constructor; struct constructor { constructor() { /* do some constructing here … */ } }; static constructor cons; }; // C++ needs to define static members externally. has_static_constructor::constructor has_static_constructor::cons; 5/28/2023 21
  • 23. Questions 1. What is a copy constructor? a) A constructor that allows a user to move data from one object to another b) A constructor to initialize an object with the values of another object c) A constructor to check the whether to objects are equal or not d) A constructor to kill other copies of a given object. 2. What happens if a user forgets to define a constructor inside a class? a) Error occurs b) Segmentation fault c) Objects are not created properly d) Compiler provides a default constructor to avoid faults/errors. 3. How many parameters does a copy constructor require? a) 1 b) 2 c) 0 d) 3 5/28/2023 23
  • 24. 5/28/2023 24 Session 2 & 3 Feature Polymorphism: Constructor overloading & Method overloading
  • 25. 5/28/2023 25 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. • 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 behaviour in different situations. This is called polymorphism.
  • 26. 5/28/2023 26 Polymorphism • Polymorphism is considered as one of the important features of Object Oriented Programming. • Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. • The word “poly” means many and “morphs” means forms, So it means many forms.
  • 27. 5/28/2023 27 Polymorphism • Overloading – Constructor Overloading – Method Overloading – Operator Overloading • Overriding – Method Overriding
  • 28. 5/28/2023 28 Constructor Overloading • In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments. This concept is known as Constructor Overloading • Overloaded constructors essentially have the same name (name of the class) and different number of arguments. • A constructor is called depending upon the number and type of arguments passed. • While creating the object, arguments must be passed to let compiler know, which constructor needs to be called.
  • 29. 5/28/2023 29 Constructor Overloading • In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments. This concept is known as Constructor Overloading • Example class construct{ public: float area; // Constructor with no parameters construct() { area = 0; } // Constructor with two parameters construct(int a, int b) { area = a * b; } void disp() { cout<< area<< endl; } }; int main() { construct o; construct o2( 10, 20); o.disp(); o2.disp(); return 1; } Output: 0 200
  • 30. 5/28/2023 30 Constructor Overloading // C++ program to demonstrate constructor overl oading #include <iostream> using namespace std; class Person { // create person class private: int age; // data member public: // 1. Constructor with no arguments Person() { age = 20; // when object is created the age will be 20 } // 2. Constructor with an argument Person(int a) { // when parameterized Constructor is called with a value the age passed will be initialized age = a; } Int getAge() { // getter to return the age return age; } }; int main() { Person person1, person2(45); // called the object of person class in differnt way cout<< "Person1 Age = " << person1.getAge() <<endl; cout<< "Person2 Age = " << person2.getAge( ) <<endl; return 0; }
  • 31. 5/28/2023 31 MCQ Questions 1. Which among the following best describes constructor overloading? a) Defining one constructor in each class of a program b) Defining more than one constructor in single class c) Defining more than one constructor in single class with different signature d) Defining destructor with each constructor Answer: c Explanation: If more than one constructors are defined in a class with same signature, then that results in error. The signatures must be different. So that the constructors can be differentiated.
  • 32. 5/28/2023 32 MCQ Questions 2. Can constructors be overloaded in derived class? a) Yes, always b) Yes, if derived class has no constructor c) No, programmer can’t do it d) No, never Answer: d Explanation: The constructor must be having the same name as that of a class. Hence a constructor of one class can’t even be defined in another class. Since the constructors can’t be defined in derived class, it can’t be overloaded too, in derived class.
  • 33. 5/28/2023 33 MCQ Questions 3. Does constructor overloading include different return types for constructors to be overloaded? a) Yes, if return types are different, signature becomes different b) Yes, because return types can differentiate two functions c) No, return type can’t differentiate two functions d) No, constructors doesn’t have any return type Answer: d Explanation: The constructors doesn’t have any return type. When we can’t have return type of a constructor, overloading based on the return type is not possible. Hence only parameters can be different.
  • 34. 5/28/2023 34 MCQ Questions 4. Why do we use constructor overloading? a) To use different types of constructors b) Because it’s a feature provided c) To initialize the object in different ways d) To differentiate one constructor from another Answer: c Explanation: The constructors are overloaded to initialize the objects of a class in different ways. This allows us to initialize the object with either default values or used given values. If data members are not initialized then program may give unexpected results.
  • 35. 5/28/2023 35 MCQ Questions 5. Which constructor will be called from the object created in the code below? class A { int i; A() { i=0; cout&lt;&lt;i; } A(int x=0) { i=x; cout&lt;&lt;I; } }; A obj1; a) Default constructor b) Parameterized constructor c) Compile time error d) Run time error ANSWER : C Explanation: When a default constructor is defined and another constructor with 1 default value argument is defined, creating object without parameter will create ambiguity for the compiler. The compiler won’t be able to decide which constructor should be called, hence compile time error.
  • 36. Method Overloading • Method overloading is a feature in C++ that allows creation of several methods with the same name but with different parameters. • For example, print(), print(int), and print("Hello") are overloaded methods. • While calling print() , no arguments are passed to the function • When calling print(int) and print("Hello") , an integer and a string arguments are passed to the called function. • Allows one function to perform different tasks 5/28/2023 36
  • 37. Types of Polymorphism • Basically, there are two types of polymorphism: – Compile time (or static) polymorphism – Run-time (or dynamic) polymorphism. • Static polymorphism -> Method overloading - calls a function using the best match technique or overload resolution. 5/28/2023 37
  • 38. Matching Function Calls With Overloaded Methods • When an overloaded function is called, one of the following cases occurs: • Case 1: A direct match is found, and there is no confusion in calling the appropriate overloaded function. • Case 2: If a match is not found, a linker error will be generated. However, if a direct match is not found, then, at first, the compiler will try to find a match through the type conversion or type casting. • Case 3: If an ambiguous match is found, that is, when the arguments match more than one overloaded function, a compiler error will be generated. This usually happens because all standard conversions are treated equal. 5/28/2023 38
  • 40. Questions 1. Which of the following permits function overloading on c++? a) type b) number of arguments c) type & number of arguments d) number of objects 2. Overloaded functions are ________________ a) Very long functions that can hardly run b) One function containing another one or more functions inside it c) Two or more functions with the same name but different number of parameters or type d) Very long functions 3. What should be passed in parameters when function does not require any parameters? a) void b) blank space c) both void & blank space d) tab space 5/28/2023 40
  • 41. Session 6, 7 & 8 Operator Overloading & Types 5/28/2023 41
  • 42. • The utility of operators such as +, =, *, /, >, <, and so on is predefined in any programming language. • Programmers can use them directly on built-in data types to write their programs. • However, these operators do not work for user-defined types such as objects. • Therefore, C++ allows programmers to redefine the meaning of operators when they operate on class objects. This feature is called operator overloading 5/28/2023 42
  • 43. Operator Overloading: Operator – It is a symbol that indicates an operation. Arithmetic operators are + (add two numbers), - (subtract two numbers), * ( Multiply two numbers), / ( Divide between two numbers). At now, we will take an Addition ‘+’ Sign, its use of ‘+’ sign is 5+5=10 2.5+2.5=5 5/28/2023 43
  • 44. ❖ Operator Overloading means multiple functions or multiple jobs. In operator overloading the ‘+’ sign use to add the two objects. ❖ One of C++’s great features is its extensibility, Operator Overloading is major functionality related to extensibility. ❖ In C++, most of operators can be overloaded so that they can perform special operations relative to the classes you create. 5/28/2023 44
  • 45. ❖ For Example, ‘+’ operator can be overloaded to perform an operation of string concatenation along with its pre-defined job of adding two numeric values. ❖ When an operator is overloaded, none of its original meaning will be lost. ❖ After overloading the appropriate operators, you can use C++’s built in data types. 5/28/2023 45
  • 46. Unary Operator - Operators attached to a single operand. (-a, +a, --a, ++a, a--, a++) Binary Operator - Operators attached to two operand. (a-b, a+b, a*b, a/b, a%b, a>b, a<b ) 5/28/2023 46
  • 47. return-type class-name:: operator op(arg-list) { function body } EXPLANATION ❖ return type – It is the type of value returned by the specified operation. ❖ op - It is the operator being overloaded. It may be unary or binary operator. It is preceded by the keyword operator. ❖ operator op - It is the function name, Where operator is a keyword. 5/28/2023 47
  • 48. Introduction One of the exciting features of C++ Works only on the single variable It can be overloaded two ways 1. Static member function 2. Friend function -,+,++,-- those are unary operator which we can overloaded. 5/28/2023 48
  • 49. Using a member function to Overload Unary Operator 5/28/2023 49
  • 50. Example Program: Write a program which will convert an positive values in an object to negative value. Code: #include <iostream.h> class demo { int x,y,z; public: void getdata (int a, int b,int c) { x=a; y=b; z=c; } Contd..., 5/28/2023 50
  • 51. void display(); void operator –(); }; void demo::display() { cout<<“x=“<<x<<“ny=“<<y<<“nz=“<<z<<endl; } void demo::operator –() { x=-x; y=-y; z=-z; } int main() { demo obj1; CONTD..., 5/28/2023 51
  • 54. INTRODUCTION In Binary operator overloading function, there should be one argument to be passed. It is overloading of an operator operating on two operands. 5/28/2023 54
  • 55. #include<iostream> class multiply { int first,second; public: void getdata(int a,int b) { first=a; second=b; } Contd..., 5/28/2023 55
  • 56. void display() { cout<<“first=“<<first<<“second=“<<secon<<endl; } multiply operator *(multiply c); }; void multiply::operator *(multiply c) { multiply temp; temp.first=first*c.first; temp.second=second*c.second; return temp; } Contd.., 5/28/2023 56
  • 58. 5/28/2023 58 MCQ Questions I. In case of operator overloading, operator function must be ______ . 1. Static member functions 2. Non- static member functions 3. Friend Functions a. Only 2 b. Only 1, 3 c. Only 2 , 3 d. All 1 , 2, 3
  • 59. 5/28/2023 59 MCQ Questions In case of operator overloading, operator function must be ______ . 1. Static member functions 2. Non- static member functions 3. Friend Functions a. Only 2 b. Only 1, 3 c. Only 2 , 3 d. All 1 , 2, 3
  • 60. 5/28/2023 60 MCQ Questions II. Using friend operator function, following perfect set of operators may not be overloaded. a. = , ( ) , [ ] , -> b. <<, = = , [ ] , >> c. ?, = , ( ) , ++ d. +,-,--,++
  • 61. 5/28/2023 61 MCQ Questions II. Using friend operator function, following perfect set of operators may not be overloaded. a. = , ( ) , [ ] , -> b. <<, = = , [ ] , >> c. ?, = , ( ) , ++ d. +,-,--,++
  • 62. 5/28/2023 62 MCQ Questions III. When overloading unary operators using Friend function,it requires_____ argument/s. a. Zero b. One c. Two d. None of these.
  • 63. 5/28/2023 63 MCQ Questions III. When overloading unary operators using Friend function,it requires_____ argument/s. a. Zero b. One c. Two d. None of these.
  • 64. 5/28/2023 64 MCQ Questions IV. In case of binary operator overloading with member function, which of following statement should be taken into consideration? a. Right hand operand must be object. b. Left hand operand must be object. c. Both the operands must be objects. d. All of these should be considered.
  • 65. 5/28/2023 65 MCQ Questions IV. In case of binary operator overloading with member function, which of following statement should be taken into consideration? a. Right hand operand must be object. b. Left hand operand must be object. c. Both the operands must be objects. d. All of these should be considered.
  • 66. 5/28/2023 66 MCQ Questions V.Which is the correct statement anout operator overloading in C++? A. Only arithmetic operators can be overloaded B. Only non-arithmetic operators can be overloaded C. Precedence of operators are changed after overlaoding D. Associativity and precedence of operators does not change
  • 67. 5/28/2023 67 MCQ Questions V. Which is the correct statement anout operator overloading in C++? A. Only arithmetic operators can be overloaded B. Only non-arithmetic operators can be overloaded C. Precedence of operators are changed after overlaoding D. Associativity and precedence of operators does not change
  • 68. Session 11 UML Sequence Diagram 5/28/2023 68
  • 69. Interaction Diagram • Interaction diagrams are used to observe the dynamic behavior of a system. • Interaction diagram visualizes the communication and sequence of message passing in the system. • Interaction diagram represents the structural aspects of various objects in the system. • Interaction diagram represents the ordered sequence of interactions within a system. • Interaction diagram provides the means of visualizing the real time data via UML. 5/28/2023 69
  • 70. • This interactive behavior is represented in UML by two diagrams known as – Sequence diagram – Collaboration diagram. • Sequence diagram emphasizes on time sequence of messages from one object to another. • Collaboration diagram emphasizes on the structural organization of the objects that send and receive messages. 5/28/2023 70
  • 71. How to Draw an Interaction Diagram? • The purpose of interaction diagrams is to capture the dynamic aspect of a system. • So to capture the dynamic aspect, we need to understand what a dynamic aspect is and how it is visualized. Dynamic aspect can be defined as the snapshot of the running system at a particular moment. • Following things are to be identified clearly before drawing the interaction diagram – Objects taking part in the interaction. – Message flows among the objects. – The sequence in which the messages are flowing. – Object organization. 5/28/2023 71
  • 72. Sequence Diagram • A sequence diagram simply depicts interaction between objects in a sequential order i.e. the order in which these interactions take place. 5/28/2023 72
  • 73. Sequence Diagram Notations Actors : An actor in a UML diagram represents a type of role where it interacts with the system and its objects. 5/28/2023 73
  • 74. 2.Lifelines :  A lifeline is a named element which depicts an individual participant in a sequence diagram. So basically each instance in a sequence diagram is represented by a lifeline.  Lifeline elements are located at the top in a sequence diagram.  lifeline follows the following format : Instance Name : Class Name 5/28/2023 74
  • 75. 3.Messages :  Communication between objects is depicted using messages. The messages appear in a sequential order on the lifeline.  We represent messages using arrows. Lifelines and messages form the core of a sequence diagram. 5/28/2023 75
  • 76. Synchronous messages  A synchronous message waits for a reply before the interaction can move forward.  The sender waits until the receiver has completed the processing of the message.  The caller continues only when it knows that the receiver has processed the previous message i.e. it receives a reply message.  A large number of calls in object oriented programming are synchronous. We use a solid arrow head to represent a synchronous message. 5/28/2023 76
  • 77. Asynchronous Messages  An asynchronous message does not wait for a reply from the receiver.  The interaction moves forward irrespective of the receiver processing the previous message or not.  We use a lined arrow head to represent an asynchronous message. 5/28/2023 77
  • 78. Create message  We use a Create message to instantiate a new object in the sequence diagram.  It is represented with a dotted arrow and create word labeled on it to specify that it is the create Message symbol. For example :  The creation of a new order on a e-commerce website would require a new object of Order class to be created. 5/28/2023 78
  • 79. Delete Message • We use a Delete Message to delete an object. • It destroys the occurrence of the object in the system. • It is represented by an arrow terminating with a x. For example – In the scenario below when the order is received by the user, the object of order class can be destroyed 5/28/2023 79
  • 80. Self Message • A message an object sends to itself, usually shown as a U shaped arrow pointing back to itself. 5/28/2023 80
  • 81. Reply Message • Reply messages are used to show the message being sent from the receiver to the sender. • We represent a return/reply message using an open arrowhead with a dotted line. • The interaction moves forward only when a reply message is sent by the receiver. 5/28/2023 81
  • 82. Found Message • A Found message is used to represent a scenario where an unknown source sends the message. • It is represented using an arrow directed towards a lifeline from an end point. 5/28/2023 82
  • 83. Lost Message • A Lost message is used to represent a scenario where the recipient is not known to the system. • It is represented using an arrow directed towards an end point from a lifeline. For example: 5/28/2023 83
  • 84. Example – Sequence Diagram 5/28/2023 84
  • 85. Questions 1. What does a message mean? a) It Passes all communications from one object to another and are represented by message arrows in sequence diagrams. b) The message goes from the sending object’s lifeline to the receiving object’s lifeline. c) It is a rectangle containing an identifier with a dashed line extending below the rectangle. d) List of all attributes. 2. What is a lifeline? a) It is a frame consisting of a rectangle with a pentagon in its upper left- hand corner b) It is a rectangle containing an identifier with a dashed line extending below the rectangle c) It is a name compartment; the interaction is represented inside the rectangle d) Emergency situation in real world approach. 5/28/2023 85
  • 87. COLLABORATION DIAGRAM depicts the relationships and interactions among software objects. They are used to understand the object architecture within a system rather than the flow of a message as in a sequence diagram. They are also known as “Communication Diagrams.” In the collaboration diagram, the method call sequence is indicated by some numbering technique. The number indicates how the methods are called one after another. Collaboration diagram 5/28/2023 87
  • 88. It is also called as a communication diagram. It emphasizes the structural aspects of an interaction diagram - how lifeline connects. Its syntax is similar to that of sequence diagram except that lifeline don't have tails. Messages passed over sequencing is indicated by numbering each message hierarchically. Compared to the sequence diagram communication diagram is semantically weak. Object diagrams are special case of communication diagram. It allows you to focus on the elements rather than focusing on the message flow as described in the sequence diagram. Sequence diagrams can be easily converted into a collaboration diagram as collaboration diagrams are not very expressive. Benefits of Collaboration Diagram 5/28/2023 88
  • 89. Example 5/28/2023 89 Following diagram represents the sequencing over student management system:
  • 90. The above collaboration diagram represents a student information management system. The flow of communication in the above diagram is given by, A student requests a login through the login system. An authentication mechanism of software checks the request. If a student entry exists in the database, then the access is allowed; otherwise, an error is returned. Example 5/28/2023 90
  • 91. 1. A collaboration diagram shows a. Structural Aspect b. Behavioral Aspect c. Environmental Aspect d. Both A and B e. Both B and C 2. which diagram is used to show interactions between messages are classified as? a.activity b.state chart c.collaboration d.object lifeline MCQ’s 5/28/2023 91
  • 92. Session 13 Inheritance & Types 5/28/2023 92
  • 93. Inheritance Inheritance is the capability of one class to acquire properties and characteristics from another class. 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. Definition 01 Type s 0 3 Single Inheritance, Multiple Inheritance, Hierarchical Inheritance, Multilevel Inheritance, and Hybrid Inheritance (also known as Virtual Inheritance) Note : All members of a class except Private, are inherited 1. Code Reusability 2. Method Overriding (Hence, Runtime Polymorphism.) 3. Use of Virtual Keyword Advantages 04 Synta x 02
  • 94. Inheritance Types Single 01 Multiple 02 Hierarchic al 03 Multilevel 04 Hybrid 05
  • 95. Modes of Inheritance 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 Public 01 private 03 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. The private members in the base class cannot be directly accessed in the derived class, while protected members can be directly accessed. Note: Protected 02 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.