0% found this document useful (0 votes)
11 views15 pages

UNIT 4 Polymorphism, Inheritance and File Handling

Uploaded by

rohankashyapmys
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)
11 views15 pages

UNIT 4 Polymorphism, Inheritance and File Handling

Uploaded by

rohankashyapmys
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/ 15

UNIT 4 Polymorphism, inheritance & File handling

Polymorphism
 Polymorphism is the ability of an object to take on many forms
 It allows different objects to respond to the same message or method call in multiple
ways
 In C++, polymorphism is achieved through method overriding and operator
overloading
 Polymorphism is defined as the ability of a message to be displayed in more than one
form
Operator overloading in C++
 Operator overloading in C++ is a compile-time polymorphism in which the operator
is overloaded to provide the special meaning to the user-defined data type
 i.e. a single operator can be used to perform different task(operator is overloaded)
 Operator overloading is achieved by defining special member functions called as
operator function
 For example, we can overload an operator ‘+’ to concatenate two strings & to add
two complex numbers
 Syntax for C++ operator overloading
return_type operator operator_symbol(arguments)
{
// body.
}
 Here, return_type is the return type of the function, operator is the keyword,
operator_symbol is the operator to be overloaded, arguments is the list of arguments
passed to the function
Rules for operator overloading
1. Only existing operators can be overloaded, but the new operators cannot be
overloaded
2. The original meaning of the operators cannot be changed
3. Precedence and associativity of the operators cannot be changed
4. The overloaded operator contains at least one operand of the user-defined data type
5. We cannot use friend function to overload certain operators. However, the member
function can be used to overload those operators
6. When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument
7. When binary operators are overloaded through a member function takes one explicit
argument, but, if they are overloaded through a friend function takes two explicit
arguments
8. The operators that cannot be overloaded are:
i. Scope resolution operator (::)
ii. Pointer-to-member operator (.*)
iii. Member access (->)
iv. Dot operator (.)
v. Ternary/conditional operator (?:)
vi. sizeof() operator
9. The operators that can be overloaded are:
+. -, ++, --, ==, [], (), !=, new, delete etc.
10. Friend functions can be used for operator overloading
Example: // WCPP to illustrate operator overloading
#include<iostream.h>
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++()
{
num = num+2;
}
void show()
{
cout<<" Count is: "<<num;
}
};
int main()
{
Test t;
++t; // calling of a function void operator ++()
t.show();
return 0;
} // output Count is: 10
Overloading of unary operator
 In C++, overloading of unary operators allows us to redefine the behavior of
operators that operate on a single operand, such as +, -, ~, !, ++, and –
 This is achieved by declaring a special function within a class, known as an operator
function, which takes no arguments or a single argument

 Example: // WCPP to illustrate unary operator overloading


#include<iostream.h>
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++()
{
num = num+2;
}
void show()
{
cout<<" Count is: "<<num;
}
};
int main()
{
Test t;
++t; // calling of a function void operator ++()
t.show();
return 0;
} // output Count is: 10

 When ++ operator is operated on object t, operator function void operator++() is


invoked
Overloading of binary operators
 The binary operators take two arguments and following example illustrates
overloading of binary operator such as +

// WACPP to illustrate binary operator overloading


#include<iostream.h>
class complex
{
private:
int real, imag;
public:
complex(int r = 0, int i = 0) // constructor
{
real = r;
imag = i;
}
complex operator+(complex const &obj)
{
complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print()
{
cout<<real<<" + i"<<imag<<'\n';
}
};
int main()
{
complex c1(10, 5); // invokes the constructor
complex c2(2, 4); // invokes the constructor
complex c3 = c1 + c2; // invokes the operator function
c3.print(); // invokes print()
return 0;
} // output 12+i 9

Inheritance in C++
 The process of deriving a new class(subclass) from old class(super class/existing
class) is called as inheritance
 Inheritance is a mechanism in which an object of child class acquires all the
properties and behaviours of an object parent class

 Here, class B is the new class/ child class derived from class A called existing class
/old class
Forms of inheritance/Types of inheritance
 C++ supports the following four types of inheritance:
1. Single Inheritance
2. Multi-level Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance
 Java does not support the multiple inheritance, Multiple inheritance is achieved with
interfaces
1.Single Inheritance
 In single inheritance, a sub-class is derived from only one super class
 In single inheritance, a derived class is inherited from a single base class as shown
figure
 Single inheritance has one Base class and one derived class
 It inherits the properties and behaviour of a single-parent class
Example:

 In the above example figure, Employee is a parent class and Executive is a child
class
 The Executive class inherits all the properties of the Employee class

Syntax:
class base_classname
{
// body of the base class
}
class derived_classname:public base_classname
{
// body of the derived class
}
Example program:
#include<iostream.h>
class Base // Base class
{
public:
int x;
void getdata()
{
cout<< "Enter the value of x = ";
cin>> x;
}
};
class Derived:public Base // Derived class (publicly inherits from Base)
{
private:
int y;
public:
void readdata()
{
cout<<"Enter the value of y = ";
cin>>y;
}
void product()
{
cout<<"Product = "<<x * y<<endl;
}
};
int main()
{
Derived d; // d is object of derived class Derived
d.getdata(); // calls getdata()
d.readdata(); // calls readdata()
d.product(); // calls product()
return 0;
}
 In above example, Base is base class and Derived is derived class. Derived inherits
all the members of Base using object d of class Derived

2.Multi-level Inheritance
 In multilevel inheritance, a class is derived from another derived class, which is also
derived from another derived class, creating a chain of inheritance
 In multilevel inheritance, a derived class is inherited from another derived class,
as shown in figure
 Multilevel Inheritance has one base class and more than two derived classes
Example:

 In the above example figure, the class Marks inherits the members / methods of the
class Student. The class Sports inherits the members of the class Marks
 Therefore, the Student class is the parent class of the class Marks and the class
Marks is the parent of the class Sports
 Hence, the class Sports implicitly inherits the properties of the class Student along
with the class Marks
Syntax:
class base_classname
{
// body of base class
}
class derived_classname1:public base_classname
{
// body of derived class 1
}
class derived_classname2:public derived_classname1
{
// body of derived class 2
}
Example program:
#include<iostream.h>
class vehicle // Base class vehicle
{
public:
void vehicle()
{
cout<<"This is a vehicle."<<endl;
}
};
class fourwheeler:public vehicle // four_wheeler is derived from vehicle
{
public:
void fourwheeler() // fourwheeler is a constructor
{
cout<<"This is a four wheeler."<<endl;
}
};
class car:public fourwheeler // Car is derived from fourwheeler
{
public:
void car() // car is a constructor
{
cout<<"This is a four wheeler."<<endl;
}
};
int main()
{
car c;
c.vehicle(); // Output: This is a vehicle
c.fourwheeler(); // Output: This is a four wheeler
c.car(); // Output: This is a car
return 0;
}

3.Hierarchical Inheritance
 If more number of classes are derived from a single base class, it is
called hierarchical inheritance
 In hierarchical inheritance, multiple classes are inherited from the same superclass
 In hierarchical inheritance, more than one derived classes are inherited from a single
base class as shown in figure
Example:

 In the above example figure, the subclasses Science, Commerce, and Arts are
inherited from a single parent class named Student
Syntax:
class base_classname
{
// body of base class
};
class derived_classname1:public base_classname
{
// body of derived class 1
};
class derived_classname2:public base_classname
{
// body of derived class 2
};
Example program:
#include<iostream.h>
class A // Base class
{
public:
int x, y;
void getdata()
{
cout<<"Enter the value of x and y= ";
cin>>x>>y;
}
};
class B:public A //B is derived class derived from base class A
{
void product()
{
cout<<"Product = "<<x * y<<endl;
}
};
class C:public A // C is derived class derived from base class A
{
public:
void sum()
{
cout<< "\nSum= " << x + y; // Perform sum
}
};
int main()
{
B b; // b is object of derived class B
C c; // c is object of derived class C
b.getdata(); // input x and y
b.product();
c.getdata();
c.sum();
return 0;
}
 In th above example, class A is base class which has two data members x and y
 It also inputs the values of the data members using the function getdata()
 Class B is derived class that inherits class A, calls the getdata() of base class and
performs the product using the inherited data members x and y
 Class C is derived class that inherits class A, calls the getdata() of base class and
performs the sum of x and y using the inherited data members x and y
4.Hybrid Inheritance
 Hybrid inheritance is the combination of two or more types of inheritance
 Hybrid inheritance is one of the inheritance types in Java which is a combination of
single & multiple inheritance(interface)

 For example, there are four classes say A, B, C, and D. Assume that the class "A" and
"B" extends the class "C". Also, another class, "D," extends the class "A"
 Here, the class "A" is a parent class for child class "D" and is also a child class for
parent class "C"
 In the above example, all the members of Class A are inherited into Class D, first via
Class B and secondly via Class C
Virtual functions
 Virtual function is a member function that is declared within a base class using the
keyword virtual and it is re-defined (overridden) by a derived class
 Virtual function is used to achieve run-time polymorphism
 Virtual function is used to tell the compiler to perform dynamic linkage/late binding
on the member function
 When we refer to a derived class object using a pointer or a reference to the base
class, we can call a virtual function for that object and execute the derived class’s
version of the member function
Example: // WCPP to illustrate virtual function
#include<iostream.h>
class base
{
public:
virtual void print()
{
cout<<" print base class\n ";
}
void show()
{
cout<<" show base class\n ";
}
};
class derived:public base
{
public:
void print()
{
cout<<" print derived class\n ";
}
void show()
{
cout<<" show derived class\n ";
}
};
int main()
{
base* b;
derived d;
b = &d;
b->print(); // virtual function is binded at run-time
b->show(); // Non-virtual function is binded at compile-time
return 0;
} // Output print derived class show base class
Rules for virtual function
1. Virtual function must be declared in the base class
2. The prototype of virtual function should be the same in the base class & derived class
3. Virtual function can be overridden in derived class
4. Virtual function can be friend function of another class
5. Virtual function cannot be static
6. Virtual function should be accessed using a pointer or reference of base class type to
achieve runtime polymorphism
7. Virtual functions can be used with pointers & references
8. Virtual functions are resolved dynamically
9. A class can have a virtual destructor but it cannot have a virtual constructor
10. The virtual function must be member of some class
Pure virtual function
 A pure virtual function is a virtual function that has no definition within the class
 Example:
virtual void display() = 0; // pure virtual function
Abstract classes
 In C++, an abstract class is a class that has at least one pure virtual function (i.e., a
function declared with = 0)
 Abstract classes are used to define a blueprint for derived classes
 An abstract class is a class that cannot be instantiated and it is implemented as a class
that has one or more pure virtual functions
 Example: // WCPP to illustrate abstract class with pure virtual function
#include<iostream.h>
class base
{
private:
int x;
public:
virtual void show() = 0; // pure virtual function
};
class derived:public base
{
public:
void show() // implementation of the pure virtual function
{
cout<<"In Derived \n";
}
};
int main(void)
{
base *b= new derived();// creating a pointer object of type base
b->show();
return 0;
}
File handling
Introduction to files
 In C++, files are essential for storing and retrieving data permanently on a storage
device
 File handling allows programs to read from and write to files, enabling data
persistence and manipulation
 File handling is used to store data permanently in a computer
 Using file handling we can store our data in secondary memory (Hard disk)
 For achieving file handling we need to follow the following steps:
Step1.naming a file
Step2.opening a file
Step3.writing data into file
Step4.reading data from file
Step5.closing a file
File opening modes
 In C++, file opening modes determine how a file is accessed and manipulated
 Common file opening modes are:
1. ios::in (Input mode)
 It opens a file for reading only, the file must already exist
2. ios::out (Output mode)
 It opens a file for writing only. If the file does not exist, it will be created. If it does
exist, its contents will be truncated
3.ios::app (Append mode)
 It opens a file for writing & appends data to the end of the file
 If the file does not exist, it will be created
4.ios::ate (Absolute position mode)
 It opens a file for reading or writing and positions the file pointer at the end of the file
5.ios::binary (Binary mode)
 It opens a file in binary format, allowing the program to read & write raw binary data
6.ios::trunc (Truncate mode)
 It opens a file for writing and truncates its contents to zero length if it already exists
7.ios::nocreate (No-create mode)
 It opens a file for reading or writing, but only if it already exists
 If the file does not exist, an error occurs
8.ios::noreplace (No-replace mode)
 It opens a file for reading or writing, but only if it does not already exist
 If the file already exists, an error occurs
Classes for file stream operations/ C++ file stream classes
 In C++, file stream operations are handled by three classes:
1. fstream
2. ifstream
3. ofstream
1.fstream
 The fstream class is a base class that provides a common interface for both input &
output operations
 It can be used for both reading & writing to files
 It is used to create files, write information to files & read information from files
 It has the capabilities of both ofstream & ifstream which means it can create files,
write information to files & read information from files
 fstream objects can be opened in various modes such as:
1. ios::in for reading (default)
2. ios::out for writing
3. ios::app for appending
4. ios::ate for seeking to the end of the file
2.ifstream
 The ifstream class is a derived class of fstream that provides input-only operations
 It is used for reading data from files
 ifstream objects can be opened in read mode (ios::in) only
 It represents the input file stream & it is used to read information from files
3. ofstream
 The ofstream class is a derived class of fstream that provides output-only operations
 It is used for writing data to files
 ofstream objects can be opened in write mode (ios::out) only
 It is used to create files & write information to the files
File I/O operations
 In C++, file input/output (I/O) operations are performed using the fstream class,
which is part of the Standard Template Library (STL)
 fstream provides a way to interact with files, allowing us to read from & write to
them
 Basic file I/O operations are:
1. Opening a file
 The open() function is used to open a file for reading (ios::in) or writing (ios::out)
 We can also open a file for both reading & writing (ios::in | ios::out)
 File must be opened before you can read from it or write to it
 Either ofstream or fstream object may be used to open a file for writing
 ifstream object is used to open a file for reading purpose only
2.Reading from a file
 The getline() function is used to read a line from a file, or the get() function to read a
single character
 To read from a file, first we have to open the specified file in reading mode
 If the file doesn’t exist, then its respective method returns NULL
3.Writing to a File
 The << operator (insertion operator) is used to write data to a file
 To write contents into a file, we will first need to open the required file
 If the specified file does not exist, then a new file will be created
4.Closing a file
 The close() function is used to close an opened file
 When a C++ program terminates it automatically releases all the allocated memory &
closes all the opened files
 The programmer should close all the opened files before program termination
5.Append a file
 To append a file in C++, we can use the std::ofstream class from the C++ standard
library
 std::ios::app specifies the append mode. If the file doesn’t exist, it will be created. If
it does exist, new content will be added to the end of the file without overwriting the
existing content

You might also like