Unit 2 Methods and Polymorphism
Unit 2 Methods and Polymorphism
Prepared by
Department of Data Science and Business
Systems & Networking and
Communications
5/28/2023 1
Session 1
5/28/2023 2
CONSTRUCTORS
• It is very common for some part of an object to require
initialization before it can be used.
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 do not have return types, not even void and they
cannot return values.
5/28/2023 6
• Constructors cannot be virtual.
5/28/2023 7
CONSTRUCTOR TYPES
5/28/2023 8
DEFAULT CONSTRUCTOR
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.
5/28/2023 11
DEFAULT CONSTRUCTOR
5/28/2023 13
PARAMETERIZED CONSTRUCTOR
OUTPUT
10
20
30
5/28/2023 14
PARAMETERIZED CONSTRUCTOR
5/28/2023 15
COPY CONSTRUCTOR
5/28/2023 16
COPY CONSTRUCTOR
5/28/2023 17
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;
};
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
Session 2 & 3
Feature Polymorphism:
Constructor overloading &
Method overloading
5/28/2023 24
Polymorphism
• The word polymorphism means having many forms.
5/28/2023 25
Polymorphism
5/28/2023 26
Polymorphism
• Overloading
– Constructor Overloading
– Method Overloading
– Operator Overloading
• Overriding
– Method Overriding
5/28/2023 27
Constructor Overloading
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
• Example
class construct{
public: int main() {
float area; construct o;
// Constructor with no parameters construct o2( 10, 20);
construct() {
area = 0; o.disp();
} o2.disp();
// Constructor with two parameters return 1;
construct(int a, int b) { }
area = a * b;
} Output:
void disp() { 0
cout<< area<< endl; 200
}
};
5/28/2023 29
Constructor Overloading
// C++ program to demonstrate constructor overl
oading Int getAge()
#include <iostream> { // getter to return the age
using namespace std; return age;
class Person { // create person class }
private: };
int age; // data member
public:
// 1. Constructor with no arguments int main()
Person() {
{ Person person1, person2(45);
// called the object of person class in differnt
age = 20; // when object is created the age will be way
20
}
// 2. Constructor with an argument cout<< "Person1 Age = " << person1.getAge()
Person(int a) <<endl;
{ // when parameterized Constructor is called with cout<< "Person2 Age = " << person2.getAge(
a value the age passed will be initialized ) <<endl;
age = a; return 0;
} }
5/28/2023 30
MCQ Questions
1. Which among the following best describes constructor overloading?
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 31
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 32
MCQ Questions
3. Does constructor overloading include different return types for
constructors to be overloaded?
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 33
MCQ Questions
4. Why do we use constructor overloading?
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 34
MCQ Questions
5. Which constructor will be called from the object created in the code
below?
class A
{ int i;
A()
{
i=0; cout<<i;
}
A(int x=0)
{
i=x; cout<<I;
}
};
A obj1; ANSWER : C
Explanation: When a default constructor is
a) Default constructor
defined and another constructor with 1 default
b) Parameterized constructor
c) Compile time error value argument is defined, creating object without
d) Run time error parameter will create ambiguity for the compiler.
The compiler won’t be able to decide which
5/28/2023
constructor should be called, hence compile 35time
error.
Method Overloading
• Method overloading is a feature in C++ that allows creation
of several methods with the same name but with different
parameters.
5/28/2023 37
Matching Function Calls With Overloaded Methods
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;
}
5/28/2023 Contd...,
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;
5/28/2023 51
CONTD...,
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;
}
5/28/2023
Contd..,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
MCQ Questions
I. In case of operator overloading, operator function must be ______ .
3. Friend Functions
a. Only 2
b. Only 1, 3
c. Only 2 , 3
d. All 1 , 2, 3
58
5/28/2023
MCQ Questions
In case of operator overloading, operator function must be ______ .
3. Friend Functions
a. Only 2
b. Only 1, 3
c. Only 2 , 3
d. All 1 , 2, 3
59
5/28/2023
MCQ Questions
II. Using friend operator function, following perfect set of operators may
not be overloaded.
a. = , ( ) , [ ] , ->
b. <<, = = , [ ] , >>
c. ?, = , ( ) , ++
d. +,-,--,++
60
5/28/2023
MCQ Questions
II. Using friend operator function, following perfect set of operators may
not be overloaded.
a. = , ( ) , [ ] , ->
b. <<, = = , [ ] , >>
c. ?, = , ( ) , ++
d. +,-,--,++
61
5/28/2023
MCQ Questions
a. Zero
b. One
c. Two
d. None of these.
62
5/28/2023
MCQ Questions
a. Zero
b. One
c. Two
d. None of these.
63
5/28/2023
MCQ Questions
64
5/28/2023
MCQ Questions
65
5/28/2023
MCQ Questions
66
5/28/2023
MCQ Questions
67
5/28/2023
Session 11
5/28/2023 68
Interaction Diagram
• Interaction diagrams are used to observe the dynamic
behavior of a system.
– Sequence diagram
– Collaboration diagram.
5/28/2023 70
How to Draw an Interaction Diagram?
• The purpose of interaction diagrams is to capture the dynamic aspect of
a system.
5/28/2023 71
Sequence Diagram
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 :
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
5/28/2023 78
Delete Message
5/28/2023 79
Self Message
5/28/2023 80
Reply Message
• Reply messages are used to show the message being sent from the
receiver to the sender.
• The interaction moves forward only when a reply message is sent by the
receiver.
5/28/2023 81
Found Message
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
5/28/2023 89
Example
5/28/2023 90
MCQ’s
5/28/2023 91
Session 13
5/28/2023 92
Inheritance
02 Synta
x
Single Inheritance, Multiple Inheritance, Hierarchical
Inheritance, Multilevel Inheritance, and Hybrid Inheritance (also
0 Type known as Virtual Inheritance)
3 s
Note : All members of a class except Private, are inherited
1. Code Reusability
04 Advantages 2. Method Overriding (Hence, Runtime Polymorphism.)
3. Use of Virtual Keyword
Inheritance Types
01 Single 02 Multiple 03 Hierarchic
al
04 Multilevel
05 Hybrid
Modes of
Inheritance
If we derive a sub class from a public base class. Then the public
01 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