Polymorphism - MCA
Polymorphism - MCA
UNIT –V
STRUCTURE
5.0. Objectives
5.1. Introduction
5.2. Polymorphism:
5.2.1. Introduction & types of polymorphism
5.2.2. Function overloading
5.2.3. operator overloading,
5.2.4. rules for overloading operators
5.2.5. overloading of unary & binary operators.
5.3. Exception Handling:
5.3.1. Try
5.3.2. Throw
5.3.3. Catch
5.3.4. Throwing and Exception
5.3.5. Catching an Exception.
5.4. Let Us Sum Up
5.5. Key Words
5.6. Some Useful Books
5.7. Answer to check your progress
5.8. Terminal Questions
5.0. OBJECTIVES
After studying this unit, you will be able to:
• Understand different types of Inheritance
• Understand the concept of Pointers
• Create Virtual Functions
• Implement polymorphism
154
OOPS using C++
5.1. INTRODUCTION
5.2. POLYMORPHISM:
For example,
Consider an example in which the function name and prototype are the
same in both base class and derived class
class X
{
int a;
public :
void show() // function in base class
{
……..
}
};
class Y: public X
{
155
OOPS using C++
int b;
public:
void show() // functionin derived class
{
………
}
};
Suppose we want to print the values of objects of both the classes X and
Y. Since the prototype of show () is the same in both the places we can’t
apply overloading principle. In such type of situations we can use the class
resolution operator to identify the class while invoking the functions using
the derived class objects.
The appropriate function can be selected while the program isexecuting,
which is known as run time polymorphism. C++ allows a mechanism
called virtual function to achieve run time polymorphism.
The appropriate function is linked with a particular class much later after
the compilation; this process is termed as late binding. It is also known as
dynamic binding because the selection of the appropriate function is done
dynamically at run time.
Following figure shows the catagories of polymorphism
Polymorphism
Compile time
Runtime
156
OOPS using C++
157
OOPS using C++
158
OOPS using C++
Python is dynamically typed (it does not require the type to be specified).
The Python addition function is an ad hoc polymorphism because it is a
single function of the same name, “+”, that works on multiple types.
Both (Python):
Copy
3+4
"Foo" + "bar"
Return a value of their corresponding types, int and String, respectively.
Copy
→7
→ "Foobar"
For values of type int, the addition function adds the two values together,
so 3+4 returns 7. For values of type String, the addition function
concatenates the two strings, so “Foo” + “bar” returns, “Foobar”.
Coercion polymorphism (Casting)
Coercion polymorphism is the direct transformation of one type into
another. It happens when one type gets cast into another type. Before,
polymorphism occurred through interacting with different types through
the object class or the functions. An object’s type could be selected when
the program was run. A single function could work with different types.
A simple example is transforming number values from ints, to doubles, to
floats, and vice versa. Depending on the programming language, either the
type can be defined on the variable, or sometimes there exists a method on
the types to convert their value to another type.
Python will convert types like this:
Copy
int(43.2) #Converts a double to an int
float(45) #Converts an int to a float
Java might convert the type simply by defining the type:
Copy
int num = 23;
double dnum = num;
or
Copy
double dnum = Double.valueOf(inum);
159
OOPS using C++
160
OOPS using C++
Output:
30
55
Let's see the simple example when the type of the arguments vary.
// Program of function overloading with different types of arguments.
1. #include<iostream>
2. using namespace std;
3. int mul(int,int);
4. float mul(float,int);
5.
6.
7. int mul(int a,int b)
8. {
9. return a*b;
10. }
11. float mul(double x, int y)
12. {
13. return x*y;
14. }
15. int main()
16. {
17. int r1 = mul(6,7);
18. float r2 = mul(0.2,3);
19. std::cout << "r1 is : " <<r1<< std::endl;
20. std::cout <<"r2 is : " <<r2<< std::endl;
21. return 0;
22. }
Output:
r1 is : 42
r2 is : 0.6
Function Overloading and Ambiguity
When the compiler is unable to decide which function is to be invoked
among the overloaded function, this situation is known as function
overloading.
161
OOPS using C++
When the compiler shows the ambiguity error, the compiler does not run
the program.
162
OOPS using C++
163
OOPS using C++
20. tt.Print();
21. return 0;
22. }
Output:
The Count is: 10
Let's see a simple example of overloading the binary operators.
// program to overload the binary operators.
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5.
6. int x;
7. public:
8. A(){}
9. A(int i)
10. {
11. x=i;
12. }
13. void operator+(A);
14. void display();
15. };
16.
17. void A :: operator+(A a)
18. {
19.
20. int m = x+a.x;
21. cout<<"The result of the addition of two objects is : "<<m;
22.
23. }
24. int main()
25. {
26. A a1(5);
27. A a2(4);
28. a1+a2;
164
OOPS using C++
29. return 0;
30. }
Output:
The result of the addition of two objects is : 9
There are some rules for the operator overloading. These rules are like
below
• Only built-in operators can be overloaded. If some operators are
not present in C++, we cannot overload them.
• The arity of the operators cannot be changed
• The precedence of the operators remains same.
• The overloaded operator cannot hold the default parameters except
function call operator “()”.
• We cannot overload operators for built-in data types. At least one
user defined data types must be there.
• The assignment “=”, subscript “[]”, function call “()” and arrow
operator “->” these operators must be defined as member
functions, not the friend functions.
• Some operators like assignment “=”, address “&” and comma “,”
are by default overloaded.
165
OOPS using C++
class check_count
{
public:
int count_plus;
int count_minus;
check_count()
{
count_plus = 0;
count_minus = 2;
};
void operator ++() { ++count_plus; } // count increment
void operator --() { --count_minus; } // count increment
};
int main()
{
check_count x, y; //creating objects
//before increment/decrement
cout << "x =" << x.count_plus<<"\n";
cout <<"y =" << y.count_minus<<"\n";
++x;
--y;
//after increment/decrement
166
OOPS using C++
cout<<"\nAfter increment/decrement\n";
cout<<"x ="<<x.count_plus<<"\n";
cout<<"y ="<<y.count_minus<<"\n";
return 0;
}
Output
class complex
{
private:
int real,imag;
public:
void getvalue()
{
cout<<"Enter the value of real number:";
cin>>real;
cout<<"Enter the value of imaginary number:";
cin>>imag;
}
complex operator+(complex obj)
167
OOPS using C++
{
complex temp;
temp.real=real+obj.real;
temp.imag=imag+obj.imag;
return(temp);
}
complex operator-(complex obj)
{
complex temp;
temp.real=real-obj.real;
temp.imag=imag-obj.imag;
return(temp);
}
void display()
{
cout<<real<<"+"<<"("<<imag<<")"<<"i"<<"\n";
}
};
int main()
{
complex c1,c2,c3,c4;
c1.getvalue();
c2.getvalue();
c3 = c1+c2;
c4 = c1-c2;
cout<<"Result is:\n";
c3.display();
c4.display();
return 0;
168
OOPS using C++
}
Output
When executing C++ code, different errors can occur: coding errors made
by the programmer, errors due to wrong input, or other unforeseeable
things.
When an error occurs, C++ will normally stop and generate an error
message. The technical term for this is: C++ will throw
an exception (throw an error).
5.3.1. Try
5.3.2. Throw
169
OOPS using C++
5.3.3. Catch
170
OOPS using C++
return (a + b);
}
int main()
{
try
{
cout << AddPositiveIntegers(-1, 2); //exception
}
catch (std::invalid_argument& e)
{
cerr << e.what() << endl;
return -1;
}
171
OOPS using C++
return 0;
}
In this C++ throw exception example, the AddPositiveIntegers() function
is called from inside the try block in the main() function.
The AddPositiveIntegers() expects two integers a and b as arguments, and
throws an invalid_argument exception in case any of them are negative.
The std::invalid_argument class is defined in the standard library in the
<stdexcept> header file. This class defines types of objects to be thrown
as exceptions and reports errors in C++ that occur because of illegal
argument values.
The catch block in the main() function catches
the invalid_argument exception and handles it.
172
OOPS using C++
return errorCode89;
}
Both catch clauses have an exception declaration of class type; the first
one is of type pushOnFull, and the second one is of type popOnEmpty. A
handler is selected to handle an exception if the type of its exception
declaration matches the type of the exception thrown. (We will see in
Chapter 19 that the types do not have to match exactly: a handler for a base
class can handle exceptions of a class type derived from the type of the
handler's exception declaration.) For example, when the pop() member
function of the class iStack throws a popOnEmpty exception, the second
catch clause is entered. After an error message is issued to cerr, the
function main() returns errorCode89.
If these catch clauses do not contain a return statement, where does the
execution of the program continue? After a catch clause has completed its
work, the execution of the program continues at the statement that follows
the last catch clause in the list. In our example, the execution of the
program continues with the return statement in main() and, after the catch
clause for popOnEmpty generates an error message to cerr, main() returns
the value 0.
int main() {
iStack stack( 32 );
try {
stack.display();
for ( int ix = 1; ix < 51; ++ix )
{
// same as before
}
}
catch ( pushOnFull ) {
cerr << "trying to push a value on a full stack\n";
}
catch ( popOnEmpty ) {
cerr << "trying to pop a value on an empty stack\n";
}
173
OOPS using C++
2. What do you call the languages that support classes but not
polymorphism?
a) Class based language
b) Procedure Oriented language
c) Object-based language
d) If classes are supported, polymorphism will always be supported
3. Which among the following is the language which supports classes but
not polymorphism?
a) SmallTalk
b) Java
c) C++
d) Ada
174
OOPS using C++
175
OOPS using C++
176
OOPS using C++
Answer: a
Explanation: It is actually the ability for a message / data to be processed
in more than one form. The word polymorphism indicates many-forms. So
if a single entity takes more than one form, it is known as polymorphism.
Answer: c
Explanation: The languages which support classes but doesn’t support
polymorphism, are known as object-based languages. Polymorphism is
such an important feature, that is a language doesn’t support this feature,
it can’t be called as a OOP language.
Answer: d
Explanation: Ada is the language which supports the concept of classes
but doesn’t support the polymorphism feature. It is an object-based
programming language. Note that it’s not an OOP language.
Answer: c
Explanation: The feature defined in question defines polymorphism
features. Here the different objects are capable of responding to the same
message in different ways, hence polymorphism.
Answer: c
Explanation: Since Student class is abstract class and class topper and
average are inheriting student, class topper and average must define the
function named calc_grade(); in abstract class. Since both the definition
are different in those classes, calc_grade() will work in different way for
same input from different objects. Hence it shows polymorphism
178
OOPS using C++
179