0% found this document useful (0 votes)
4 views26 pages

Unit 3 Half

Unit 3 covers Polymorphism and Inheritance in C++ programming, detailing concepts such as compile-time and run-time polymorphism, function overloading, operator overloading, and function overriding. It explains how polymorphism allows methods to operate on different data types and how inheritance enables the creation of new classes based on existing ones. The unit also discusses the constraints of multiple inheritance and the use of abstract base classes and pure virtual functions.

Uploaded by

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

Unit 3 Half

Unit 3 covers Polymorphism and Inheritance in C++ programming, detailing concepts such as compile-time and run-time polymorphism, function overloading, operator overloading, and function overriding. It explains how polymorphism allows methods to operate on different data types and how inheritance enables the creation of new classes based on existing ones. The unit also discusses the constraints of multiple inheritance and the use of abstract base classes and pure virtual functions.

Uploaded by

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

Unit 3

Object Oriented
Programming Using C++

Dr. Dheresh Soni


UNIT 3
Polymorphism and Inheritance
• Syllabus: Polymorphism • Constraints of multiple
• Compile time polymorphism inheritance
• Run time polymorphism • Abstract base class
• Function overloading • Pure virtual functions
• Operator overloading
• Function overriding
• Inheritance
• Types of inheritance
• Constructors and destructors in
inheritance
Polymorphism
• Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the
ability to take more than one form. An operation may exhibit different behaviours in
different instances. The behaviour depends upon the types of data used in the operation.
• For example, consider the operation of addition. For two numbers, the operation will
generate a sum. If the operands are strings, then the operation would produce a third string
by concatenation. The process of making an operator to exhibit different behaviours in
different instances is known as operator overloading.
• Polymorphism plays an important role in allowing objects having different internal structures
to share the same external interface. This means that a general class of operations.
• A single function name can be used to handle different number and different types of
arguments. This is something similar to a particular word having several different meanings
depending on the context. Using a single function name to perform d types of tasks is known
function overloading.

Polymorphism
Compile time polymorphism
• Compile time polymorphism is also known as Early binding, Static binding and this is same
as concept of overloading.
• There are two type of function in this concept first is calling function and second is called
function. main( ) function is calling function and class function is called function (as in
example void add(int a, int b), void add(int a, int b, int c) is called function).
• Binding refers to the linking of a called function (procedure call) to the code to be executed
in response to the calling function call.
• In static binding when called function (as in example void add(int a, int b), void add(int a, int
b, int c) ) is call by calling function (main ( ) function) then which function is to respond to
calling function is known at the time of call.
• So at the time of compilation the called function respond and attached with calling function.
So it is known as compile time polymorphism. As called function respond and attached with
calling function call at compile time so it is known as Static Binding.
• In compile time polymorphism called function response to calling function at the time of
compilation i.e. before program executes, so it is also known as Early Binding.
Compile time polymorphism
• In compile time polymorphism two are more same function name is defined in class but
parameter should be different in each function (as stated in example). When function is
called appropriate prototype is matched and when prototype matches then function get
called. This is also a concept of overloading.
#include<iostream.h>
#include<conio.h>
class test
{
public:
void sum(int a,int b)
{
cout<<"...compile time polymorphism-function overloading...\n\n";
cout<<" Enter the value of a:";
cin>>a;
cout<<" Enter the value of b:";
cin>>b;
cout<<" Sum is: "<< a+b<<"\n";
Compile time polymorphism
}
void sum(int a, int b, int c) test t;
{ t.sum(i,j);
cout<<" Enter the value of a:"; t.sum(x,y,z);
cin>>a; getch();
cout<<" Enter the value of b:"; }
cin>>b;
cout<<" Enter the value of c:";
cin>>c;
cout<<" Sum is: "<< a+b+c<<"\n\n";
}
};
void main()
{
int x,y,z,i,j;
clrscr();
Run time polymorphism
• Run time polymorphism is also known as late binding, Dynamic Binding and this is same as
concept of overriding.
• There are two type of function in this concept first is calling function and second is called
function. main( ) function is calling function and class function is called function (as in
example void show( ) is called function).
• Binding refers to the linking of a called function (procedure call) to the code to be executed
in response to the calling function call.
• In dynamic binding when called function ( as in example void show( ) ) is call by calling
function (main ( ) function) then which function is to respond to calling function is not
known until the time of the call. It is known when program start in execution i.e. at run-time.
So it is known as runtime polymorphism.
• As called function respond and attached with calling function call at run time so it is known
as Dynamic Binding. In compile time polymorphism called function response to calling
function at the time of compilation i.e. before program executes, but in run time
polymorphism called function do not respond at compile time, it respond at the time of
program execution so it is known as Late Binding.
Run time polymorphism
• In run time polymorphism when same function name is defined in base class and derived
class, this is also known as overriding concept. The function of base class is preceded with
keyword virtual to differentiate the function call. When we call function from main then we
use pointer to call function.
• A function associated with a polymorphic reference depends on the dynamic type of that
reference. At run-time the code matching the object under current reference will be called.
#include<iostream.h>
#include<conio.h>
class Base
{
public:
int i,j;
virtual void show()
{
cout<<" I am class Base \n";
cout<<"enter the value of i: ";
Run time polymorphism
cin>>j;
cin>>i;
cout<<"Answer is: "<<i*j;
cout<<"enter the value of j: ";
}
cin>>j;
};
cout<<"Answer is: "<<i+j;
void main()
}
{
};
clrscr();
class Derived: public Base
Base b;
{
Base *p,*q;
public:
p=&b;
int i,j;
p->show();
void show()
cout<<"\n\n";
{
Derived d;
cout<<"I am class Derived \n";
q=&d;
cout<<"enter the value of i: ";
q->show();
cin>>i;
getch();
cout<<"enter the value of j: ";
}
Function overloading
• As stated earlier overloading refers to the use of the same thing for different purposes. C++
also permits overloading of functions. This means that we can use the same function name
to create functions that perform a variety of different tasks. This is known as function
polymorphism in OOP.
• Using the concept of function overloading; we can design a family of functions with one
function name but with different argument lists. The function would perform different
operations depending on the argument list in the function call.
• The correct function to be invoked is determined by checking the number and type of the
arguments but not on the function type. For example, an overloaded add( ) function handles
different types of data as shown below:
• // Declarations
int add(int a, int b); // prototype 1
int add{int a, int b, int c); // prototype 2
double add(double x, double y); // prototype 3
double add(int p, double q); // prototype 4
double add(double p, int q); // prototype 5
Function overloading
• // Function calls
cout <<add(5, 10); //uses prototype 1
cout <<add(15, 10, 0); //uses prototype 4
cout <<add(12.5, 7.5); //uses prototype 3
cout <<add(5, 10, 15); //uses prototype 2
cout <<add(0.75, 5) //uses prototype 5
• A function call first matches the prototype having the same number and type of arguments
and then calls the appropriate function for execution, A best match must be unique. The
function selection involves the following steps;
• The compiler first tries to find an exact match in which the types of actual arguments
are the same, and use that function.
• If an exact match is not found, the compiler uses the integral promotions to the actual
arguments, such as, char to int, float to double to find a match.
• When either of them fails the compiler tries to use the built-in conversions to the actual
arguments and then uses the function whose match is unique. If the conversion is
possible to have multiple matches, then the compiler will generate an error message.
Function overloading
• Suppose we use the following two functions;
• long square (long n)
• double square(double x)
• A function call such as square(10) will cause error because int argument can be converted to
either long or double, thereby creating an ambiguous situation as to which version of
square( ) should be used.
• If all of the steps fail, then the compiler will try the user-defined conversions combination
with integral promotions and built-in conversions to find a unique match, User-defined
conversions are often used in handling objects. Program to illustrates function overloading.
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
#define pi 3.14
class fn
{
public:
Function overloading
void area(int); cout<<"Area of triangle:" ;
void area(int,int); cout<<t*a*b;
void area(float ,int,int); }
}; void main()
void fn::area(int a) {
{ int a,b,r;
cout<<"Area of Circle:"; clrscr();
cout<<pi*a*a; fn obj;
} cout<<"Function Overloading\n\n";
void fn::area(int a,int b) cout<<"Enter Radius of the Circle:";
{ cin>>r;
cout<<"Area of rectangle:"; obj.area(r);
cout<<a*b; cout<<"Enter 1st Sides of the Rectangle:";
} cin>>a;
void fn::area(float t,int a,int b) cout<<"Enter 2nd Sides of the Rectangle:";
{ cin>>b;
Function overloading
obj.area(a,b);
cout<<"Enter 1st Sides of the Triangle:";
cin>>a;
cout<<"Enter 2nd Sides of the Triangle:";
cin>>b;
obj.area(0.5,a,b);
getch();
}
Operator overloading
• Overloading means assigning different meanings to an operation, depending on the context.
Operator overloading is one of the important technique that has enhanced the power of
extensibility of C++.
• Operator overloading provides a flexible option for the creation of new definitions for most
of the operator. We can almost create a new language of our own by the creative use of the
function and operator overloading techniques. We can overload (give additional meaning to)
all the C++ operators except the following:

• Class member access operators (., .*)


• Scope resolution operator (::)
• Size operator (sizeof)
• Conditional operator (?:)
• Although the semantics of an operator can be extended, we cannot change its syntax, the
grammatical rules that govern its use such as the number of operands, precedence and
associativity.
Operator overloading
• To define an additional task to an operator, we must specify what it means in relation to the
class to which the operator is applied. This is done with the help of a special function, called
operator function. The general form of an operator function is:
return type classname :: operator op(arglist)
{
Function body // task defined
}
• where return type is the type of value returned by the specified operation and op is the
operator being overloaded. The op is preceded by the keyword operator. operator op is the
function name.
• The process of overloading involves the following steps:

• Create a class that defines the data type that is to be used in the overloading operation.
• Declare the operator function operator op( ) in the public part of the class.
• Define the operator function to implement the required operations.
Operator overloading
• Rules for Overloading Operators
• Although it looks simple to redefine the operators, there are certain restrictions and
limitations in overloading them. Some of them are listed below:
• Only existing operators can be overloaded. New operators cannot be created.
• The overloaded operator must have at least one operand that is of user-defined type.
• We cannot change the basic meaning of an operation That is to say, we cannot redefine
the plus (+) operator to Subtract one value from the other.
• Overloaded operators follow the syntax rules of the original operators. They cannot
overridden.
• There are some operators that cannot be overloaded.
• We cannot use friend functions to overload certain operators, However, member
functions can be used to overload them.
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
class Distance
Operator overloading
{ void displayDistance()
private: {
int feet; cout<<"Entered feet value is: “;
int inches; cout << feet<<”\n”;
public: cout<<"Entered inches value is: “;\
Distance() cout << inches<<”\n\n”;
{ } Distance D1(11, 10), D2(-5,
feet = 0; Distance operator-() 11);
inches = 0; { clrscr();
} feet = -feet; -D1;
Distance(int f, int i) inches = -inches; D1.displayDistance();
{ return Distance(feet, inches); -D2;
feet = f; } D2.displayDistance();
inches = i; }; getch();
} void main() }
{
Function overriding
• A function is a block of statements that together performs a specific task
by taking some input and producing a particular output.

• Function overriding in C++ is termed as the redefinition of base class


function in its derived class with the same signature i.e. return type and
parameters.

• Function overriding is a type of polymorphism in which we redefine the


member function of a class which it inherited from its base class. The
function signature remains same but the working of the function is
altered to meet the needs of the derived class.

• So, when we call the function using its name for the parent object, the
parent class function is executed. But when we call the function using the
child object, the child class version will be executed.
Function overriding
• Types of Function Overriding in C++ - Unlike other languages such as
Java where function overriding is strictly done at compile time, C++
supports two types of function overriding:
1. Compile Time Overriding 2. Runtime Function Overriding
• Compile Time Function Overriding - In compile time function overriding,
the function call and the definition is binded at the compilation of the
program. Due to this, it is also called early binding or static binding..

• Syntax
class Parent
{
access_modifier :
return_type name_of_the_function() { } // overridden function
};
Function overriding
class child : public Parent
{
access_modifier :
return_type name_of_the_function() { } // overriding function
};

• Example:
#include <iostream.h>
class Parent
{
public:
void Test()
{ cout << "Base Function" << endl; }
Function overriding
};
class Child : public Parent
{
public:
void Test()
{ cout << "Derived Function" << endl; }
};
int main()
{
Child Child_Derived; or Parent p;
Child_Derived.Test(); or p.Test()
return 0;
}
Function overriding
• Runtime Function Overriding using Virtual Function -Function
overriding can also be performed at the runtime, which means that
function call will be binded to its definition during runtime (also known as
late binding or dynamic binding). This can be done with the help of virtual
functions.

• Syntax: class Derived : public Base


class Base {
{ public:
public: func() //override
virtual func() { // new definition }
{ // definition } };
};
Function overriding
• Here, override keyword tells the compiler that the given overridden
function should be declared as virtual in the parent class.

• It is a kind of double check as the program can compile without errors


even if the function is not virtual. But then, it will be compile time
polymorphism and we won’t get the desired behaviour of the function
overriding.
Example:
#include <iostream.h>
class Base
{
public:
virtual void display()
{ cout << "Display method of Base class" << endl; }
virtual ~Base() { }
};
Function overriding
class Derived : public Base
{
public:
void display() //override
{ cout << "Display method of Derived class" << endl; }
};

int main()
{
Base *basePtr;
Base b_obj;
Derived derivedObj;
basePtr = &derivedObj; or basePtr = &b_obj;
basePtr->display();
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy