OOPs With C--_CSE 2001_ Unit 3.Pptx
OOPs With C--_CSE 2001_ Unit 3.Pptx
By:
Dr. Ramraj Dangi
● Introduction to object oriented
approach
● Classes and objects
Chapters ● Polymorphism and Inheritance
● Exception handling and Templates
● IOstreams and Files
Polymorphism
– compile time polymorphism
– function overloading
– operator overloading.
Syllabus Inheritance
– types of inheritance
– constructors and destructors in inheritance
– constraints of multiple inheritance
Binding means matching the function call with the correct function definition by the compiler. It takes
place either at compile time or at runtime.
Early Binding
In early binding, the compiler matches the function call with the correct function definition at compile
time. It is also known as Static Binding or Compile-time Binding. By default, the compiler goes to the
function definition which has been called during compile time. So, all the function calls you have studied
till now are due to early binding.
Example
In the case of late binding, the compiler matches the function call with the correct function definition at
runtime. It is also known as Dynamic Binding or Runtime Binding.
In late binding, the compiler identifies the type of object at runtime and then matches the function call
with the correct function definition.
By default, early binding takes place. So if by any means we want to tell the compiler to perform late
binding, then how the problem in the previous example can be solved?
Virtual Function is a member function of the base class which is overridden in the derived class. The
compiler performs late binding on this function.
To make a function virtual, we write the keyword virtual before the function definition.
Example
It is also known as overloading, early binding and static binding. It is also known as overriding, Dynamic binding and late binding.
Overloading is a compile time polymorphism where more than one Overriding is a run time polymorphism where more than one method is
method is having the same name but with the different number of having the same name, number of parameters and the type of the
parameters or the type of the parameters. parameters.
It is achieved by function overloading and operator overloading. It is achieved by virtual functions and pointers.
It provides fast execution as it is known at the compile time. It provides slow execution as it is known at the run time.
It is less flexible as mainly all the things execute at the compile time. It is more flexible as all the things execute at the run time.
● Function Overloading is defined as the process of having two or more function with the same
name, but different in parameters is known as function overloading in C++.
● In function overloading, the function is redefined by using either different types of arguments or a
different number of arguments.
● It is only through these differences, compiler can differentiate between the functions.
● The advantage of Function overloading is that it increases the readability of the program because
you don't need to use different names for the same action.
Rules of Function Overloading
The above three cases are valid cases of overloading. We can have any number of functions, but
remember that the parameter list must be different.
For example:
int mul(int, int)
double mul(int, int)
Note: As the parameter list is the same, this is not allowed. Even though their return types are different,
it’s not valid.
Example
#include<iostream>
using namespace std;
int mul(int,int);
int mul(float,int);
● A C++ virtual function is a member function in the base class that you redefine in a derived class.
It is declared using the virtual keyword.
● It is used to tell the compiler to perform dynamic linkage or late binding on the function.
● There is a necessity to use the single pointer to refer to all the objects of the different classes. So,
we create the pointer to the base class that refers to all the derived objects. But, when base class
pointer contains the address of the derived class object, always executes the base class function.
This issue can only be resolved by using the 'virtual' function.
● A 'virtual' is a keyword preceding the normal declaration of a function.
● When the function is made virtual, C++ determines which function is to be invoked at the runtime
based on the type of the object pointed by the base class pointer.
S.No. Function Overloading Function Overriding
The concept through which we can define two or more The concept through which we define a function in parent
functions with the same name and different numbers and class and the child class with the same return type and
1. parameters is known as function overloading. parameters is known as function overriding.
It can take place without inheritance. It can take place only when a class inherited from another
2. class.
3. It happens during compile time. It happens during run time.
4. It is also known as compile time polymorphism. It is also known as run time polymorphism.
The function overloading can take place multiple times. Function overriding can take place in the derived class only at
5. once.
Here, the scope of the overloaded functions remain the Here, the scope of the overridden function is different.
6. same.
No keyword is used during function overloading. When the function is defined, it is preceded by 'virtual'
7. keyword in main class.
When the compiler is unable to decide which function is to be invoked among the overloaded function,
this situation is known as function overloading ambiguity.
#include<iostream>
The above example shows an error "call of
using namespace std;
void fun(int); overloaded 'fun(double)' is ambiguous". The
void fun(float);
fun(12) will call the first function. The fun(1.2)
void fun(int i)
{ calls the second function according to our
std::cout << "Value of i is : " <<i<< std::endl;
prediction. But, this does not refer to any
}
void fun(float j) function as in C++, all the floating point
{
constants are treated as double not as a float. If
std::cout << "Value of j is : " <<j<< std::endl;
} we replace float to double, the program works.
int main()
Therefore, this is a type conversion from float
{
fun(12); //Value of i is : 12 to double.
fun(1.2); //Value of j is : 1.2
return 0;
}
Function with default arguments ambiguity in Function Overloading
#include<iostream>
using namespace std; The above example shows an error "call of
void fun(int); overloaded 'fun(int)' is ambiguous". The fun(int
void fun(int,int);
void fun(int i) a, int b=9) can be called in two ways: first is by
{ calling the function with one argument, i.e.,
std::cout << "Value of i is : " <<i<< std::endl;
} fun(12) and another way is calling the function
void fun(int a,int b=9) with two arguments, i.e., fun(4,5). The fun(int
{
std::cout << "Value of a is : " <<a<< std::endl; i) function is invoked with one argument.
std::cout << "Value of b is : " <<b<< std::endl; Therefore, the compiler could not be able to
}
int main() select among fun(int i) and fun(int a,int b=9).
{
fun(12);
return 0;
}
Function with pass by reference ambiguity in Function Overloading
#include <iostream>
using namespace std; The above example shows an error "call of
void fun(int); overloaded 'fun(int&)' is ambiguous". The
void fun(int &);
int main() first function takes one integer argument and
{ the second function takes a reference parameter
int a=10;
fun(a); // error, which f()? as an argument. In this case, the compiler does
return 0; not know which function is needed by the user
}
void fun(int x) as there is no syntactical difference between the
{ fun(int) and fun(int &).
std::cout << "Value of x is : " <<x<< std::endl;
}
void fun(int &b)
{
std::cout << "Value of b is : " <<b<< std::endl;
}
Operator Overloading
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test() {
num = 8; }
void operator ++() {
num = num+2;
}
void print() {
cout<<"The Count is: "<<num;
}
};
int main() {
Test tt;
tt.print(); //The count is: 8
++tt; // calling of a function "void operator ++()"
tt.print(); //The count is:10
return 0;
}
Example: Overloading Binary Operator
#include<iostream>
using namespace std;
class A {
private:
int a;
public:
void set_a();
void get_a();
friend A operator *(A,A); //Binary operator * overloaded friend function, which takes
two object of A and returns an object of A type.
};
void A :: set_a() {
a = 5;
}
void A :: get_a() {
cout<< a <<"\n";
}
Example: Overloading binary operator * using friend function
int main() {
A ob1, ob2;
ob1.set_a();
ob2.set_a();
A ob3 = ob1 * ob2; //ob1 and ob2 objects are passed as an argument to the operator * overloaded friend function.
cout<<"The value of a after calling operator overloading function * is : ";
ob3.get_a();
}
Example
● A C++ virtual function is a member function in the base class that you redefine in a derived class.
It is declared using the virtual keyword.
● It is used to tell the compiler to perform dynamic linkage or late binding on the function.
● There is a necessity to use the single pointer to refer to all the objects of the different classes. So,
we create the pointer to the base class that refers to all the derived objects. But, when base class
pointer contains the address of the derived class object, always executes the base class function.
This issue can only be resolved by using the 'virtual' function.
● A 'virtual' is a keyword preceding the normal declaration of a function.
● When the function is made virtual, C++ determines which function is to be invoked at the runtime
based on the type of the object pointed by the base class pointer.
Rules of Virtual Function
● A virtual function must be defined in the base class, even though it is not used.
● The prototypes of a virtual function of the base class and all the derived classes must be
identical. If the two functions with the same name but different prototypes, C++ will consider
them as the overloaded functions.
Example
● A virtual function is not used for performing any task. It only serves as a placeholder.
● When the function has no definition, such function is known as "do-nothing" function.
● The "do-nothing" function is known as a pure virtual function. A pure virtual function is a
function declared in the base class that has no definition relative to the base class.
● A class containing the pure virtual function cannot be used to declare the objects of its own, such
classes are known as abstract base classes.
● The main objective of the base class is to provide the traits to the derived classes and to create the
base pointer used for achieving the runtime polymorphism.
Pure Virtual Function
A virtual function is a member function in a base class that can be A pure virtual function is a member function in a base class whose
redefined in a derived class. declaration is provided in a base class and implemented in a
derived class.
The classes which are containing virtual functions are not abstract The classes which are containing pure virtual function are the
classes. abstract classes.
In case of a virtual function, definition of a function is provided In case of a pure virtual function, definition of a function is not
in the base class. provided in the base class.
The base class that contains a virtual function can be instantiated. The base class that contains a pure virtual function becomes an
abstract class, and that cannot be instantiated.
If the derived class will not redefine the virtual function of the If the derived class does not define the pure virtual function; it will
base class, then there will be no effect on the compilation. not throw any error but the derived class becomes an abstract class.
All the derived classes may or may not redefine the virtual All the derived classes must define the pure virtual function.
function.
Abstract Class is a class which contains at least one Pure Virtual function in it. Abstract classes are
used to provide an Interface for its subclasses.
We cannot create objects of an abstract class.
However, we can derive classes from them, and use their data members and member functions (except
pure virtual functions).
Abstract Base Class: Characteristics
● Abstract class cannot be instantiated, but pointers and references of Abstract class type can be
created.
● Abstract class can have normal functions and variables along with a pure virtual function.
● Abstract classes are mainly used for Up casting, so that its derived classes can use its interface.
● Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will
become Abstract too.
Inheritance
Definition
In C++, inheritance is a process in which one object acquires all the properties and behaviors
of its parent object automatically. In such way, you can reuse, extend or modify the attributes
and behaviors which are defined in other class.
In C++, the class which inherits the members of another class is called derived class and the
class whose members are inherited is called base class. The derived class is the specialized
class for the base class.
Advantage of C++ Inheritance
Code reusability: Now you can reuse the members of your parent class. So, there is no need
to define the member again. So less code is required in the class.
Types of Inheritance
● Single inheritance
● Multilevel inheritance
● Multiple inheritance
● Hierarchical inheritance
● Hybrid inheritance
Derived Class
A Derived class is defined as the class derived from the base class.
visibility mode: The visibility mode specifies whether the features of the base class are publicly inherited or privately
inherited. It can be public or private.
● When the base class is privately inherited by the derived class, public members of the base
class becomes the private members of the derived class. Therefore, the public members of
the base class are not accessible by the objects of the derived class. It can only be accessible
by the member functions of the derived class.
● When the base class is publicly inherited by the derived class, public members of the base
class also become the public members of the derived class. Therefore, the public members
of the base class are accessible by the objects of the derived class as well as by the member
functions of the base class.
Single Inheritance
Derived
When one class inherits another class, it is known as single level inheritance. Let's see the
example of single level inheritance which inherits the fields only.
#include <iostream>
int main() {
using namespace std;
Programmer p1;
class Account {
cout<<"Salary: "<<p1.salary<<endl;
public:
cout<<"Bonus: "<<p1.bonus<<endl;
float salary = 60000;
cout<<“Total:”<< p1.salary+ p1.bonus;
};
return 0;
class Programmer : public Account {
}
public: Output:
float bonus = 5000; Salary: 60000
Bonus: 5000
};
Total:65000
Let's see another example of single level inheritance.
The private member is not inheritable. If we Visibility modes can be classified into three
categories:
modify the visibility mode by making it
public, but this takes away the advantage of
data hiding.
#include <iostream>
using namespace std;
CAR BIKE
}
Multiple Inheritance
#include <iostream> class B
using namespace std; {
class A protected:
{ int b;
protected: public:
int a; void get_b(int n)
public: {
void get_a(int n) b = n;
{ }
a = n; };
}
};
Multiple Inheritance
class C : public A, public B int main()
{ {
public: C c;
void display() c.get_a(10);
{ c.get_b(20);
std::cout << "The value of a is : " <<a<< std::endl; c.display();
std::cout << "The value of b is : " <<b<< std::endl;
cout<<"Addition of a and b is : "<<a+b; return 0;
} }
};
Practice Question
Create two classes named Mammals and MarineAnimals. Create another class named BlueWhale
which inherits both the above classes.
Now, create a function in each of these classes which prints "I am mammal", "I am a marine
animal" and "I belong to both the categories: Mammals as well as Marine Animals" respectively.
Now, create an object for each of the above class and try calling
We want to calculate the total marks of each student of a class in Physics,Chemistry, Mathematics,
English and Computer and the average marks of the class. The number of students in the class are
entered by the user. Create a class named Marks with data members for roll number, name and
marks. Create five other classes inherited by the Marks class, namely Physics, Chemistry,
Mathematics, English and Computer which are used to define marks in individual subject of each
student. Roll number of each student will be generated automatically.
Physics Chemistry Mathematics English Computer
Marks
roll number
name
marks
Ambiguity in Multiple Inheritance
The most obvious problem with multiple inheritance occurs during function overriding.
Suppose, two base classes have a same function which is not overridden in derived class.
If you try to call the function using the object of the derived class, compiler shows error.
It's because compiler doesn't know which function to call. For example,
Ambiguity in Multiple Inheritance
int main() {
Rectangle r;
Output:
Triangle t;
Enter the length and breadth of a rectangle:
int length,breadth,base,height;
15
cout << "Enter the length and breadth of a rectangle: " <<endl;
10
cin>>length>>breadth;
Area of the rectangle is : 150
r.get_data(length,breadth);
Enter the base and height of the triangle:
int m = r.rect_area();
10
cout << "Area of the rectangle is : " <<m<<endl;
12
cout << "Enter the base and height of the triangle: " <<endl;
Area of the triangle is : 60
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
cout <<"Area of the triangle is : " << n<<endl;
return 0;
}
Hybrid Inheritance
int main()
{
D d;
d.mul();
return 0;
}
Diamond Problem
➢ Diamond Problem
➢ Diamond of Death
➢ Disinheritance
➢ Virtual base class
➢ Virtual Inheritance
Base class Default Constructor in Derived class Constructors
When we derive a class from the base class then all the data members of the base class
will become a member of the derived class. We use the constructor to initialize the data
members and here the obvious case is when the data is inherited into the derived class
who will be responsible to initialize them? To initialize the inherited data members
constructor is necessary and that's why the constructor of the base class is called first. In
the program given below, we can see the sequence of execution of constructors in
inheritance is given below:
Constructor Example
class Mammals
{
public:
Mammals(){cout<<"Mammals obj created "<<endl;}
void Mammals_statement(){cout<<"I am a mammal. "<<endl;}
};
class Marine_animals
{
public:
Marine_animals(){cout<<"Marine_animals obj created "<<endl;}
void Marine_animals_statement(){cout<<"I am a marine animal. "<<endl;}
};
int main()
Output:
{
Mammals m1;
m1.Mammals_statement();
cout<<"_______________________________________________"<<endl;
Marine_animals m_a1;
m_a1.Marine_animals_statement();
cout<<"_______________________________________________"<<endl;
Blue_whale bw1;
bw1.Blue_whale_statement();
bw1.Marine_animals_statement();
bw1.Mammals_statement();
cout<<"_______________________________________________"<<endl;
return 0;
}
Base class Parameterized Constructor in Derived class Constructor:
Let's see how we can call the parameterized constructor in the Derived
class, We need to explicitly define the calling for the parameterized
constructor of the derived class using : operator while defining the
parameterized constructor in a derived class.
Constructor Example
● Construction always starts with the base class. If there are multiple base classes
then, construction starts with the leftmost base. If there is a virtual inheritance then
it's given higher preference.
● Then the member fields are constructed. They are initialized in the order they are
declared
● Finally, the class itself is constructed
● The order of the destructor is exactly the reverse