Class : BCA 3rd Semester Course Code: BCA-S3-03
Course Title: Object Oriented Programming Concepts in C++
Unit IV
Polymorphism
The word polymorphism means having many forms. Typically, polymorphism occurs when there is a
hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different function to be executed
depending on the type of object that invokes the function.
Consider the following example where a base class has been derived by other two classes:
#include using namespace std; class Shape { protected: int width, height; public: Shape( int a = 0, int b = 0) { width = a; height = b; } int area() { cout
return (width * height / 2); } }; // Main function for the program int main( ) { Shape *shape; Rectangle rec(10,7); Triangle tri(10,5); // store the address of Rectangle shape = &rec; // call rectangle area. shape->area(); // store the address of Triangle shape = &tri; // call triangle area. shape->area(); return 0; } When the above code is compiled and executed, it produces the following result:
Parent class area
Parent class area
The reason for the incorrect output is that the call of the function area() is being set once by the
compiler as the version defined in the base class. This is called static resolution of the function call,
or static linkage - the function call is fixed before the program is executed. This is also sometimes
called early binding because the area() function is set during the compilation of the program.
But now, let's make a slight modification in our program and precede the declaration of area() in the
Shape class with the keyword virtual so that it looks like this:
class Shape { protected: int width, height; public: Shape( int a = 0, int b = 0) { width = a; height = b; }
virtual int area() { cout
The = 0 tells the compiler that the function has no body and above virtual function will be called pure
virtual function.
Early binding
Most of the function calls the compiler encounters will be direct function calls. A direct function call is a
statement that directly calls a function. For example:
#include void PrintValue(int nValue) { std::cout nX;
int nY; cout > nY; int nOperation; do { cout > nOperation; } while (nOperation < 0 || nOperation > 2); int nResult = 0; switch (nOperation) { case 0: nResult = Add(nX, nY); break; case 1: nResult = Subtract(nX, nY); break; case 2: nResult = Multiply(nX, nY); break; } cout
Example of Abstract Class
class Base //Abstract base class { public: virtual void show() = 0; //Pure Virtual Function }; class Derived:public Base { public: void show() { cout show(); } Output :
Implementation of Virtual Function in Derived class
In the above example Base class is abstract, with pure virtual show() function, hence we cannot create
object of base class.
Data File Handling In C++
File. The information / data stored under a specific name on a storage device, is called a file.
Stream. It refers to a sequence of bytes.
Text file. It is a file that stores information in ASCII characters. In text files, each line of text is terminated
with a special character known as EOL (End of Line) character or delimiter character. When this EOL
character is read or written, certain internal translations take place.
Binary file. It is a file that contains information in the same format as it is held in memory. In binary files,
no delimiters are used for a line and no translations occur here.
Classes for file stream operation
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Opening a file
OPENING FILE USING CONSTRUCTOR
ofstream outFile("sample.txt"); //output only
ifstream inFile(“sample.txt”); //input only
OPENING FILE USING open() method
Stream-object.open(“filename”, mode)
ofstream outFile;
outFile.open("sample.txt");
ifstream inFile;
inFile.open("sample.txt");
The mode parameter can have different interpretations as under
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the
file example.bin in binary mode to add data we could do it by the following call to member function
open():
fstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
Closing File
File mode parameter Meaning
ios::app Append to end of file
ios::ate go to end of file on opening
ios::binary file open in binary mode
ios::in open file for reading only
ios::out open file for writing only
ios::nocreate open fails if the file does not exist
ios::noreplace open fails if the file already exist
ios::trunc delete the contents of the file if it exist
outFile.close();
inFile.close();
INPUT AND OUTPUT OPERATION
put() and get() function
the function put() writes a single character to the associated stream. Similarly, the function get() reads a
single character form the associated stream.
example :
file.get(ch);
file.put(ch);
write() and read() function
write() and read() functions write and read blocks of binary data.
example:
file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));
ERROR HANDLING FUNCTION
FUNCTION RETURN VALUE AND MEANING
eof() returns true (non zero) if end of file is encountered while reading;
otherwise return false(zero)
fail() return true when an input or output operation has failed
bad() returns true if an invalid operation is attempted or any
unrecoverable error has occurred.
good() returns true if no error has occurred.
File Pointers And Their Manipulation
All i/o streams objects have, at least, one internal stream pointer:
ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in
the next input operation.
ofstream, like ostream, has a pointer known as the put pointer that points to the location where the
next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from
both istream and ostream).
These internal stream pointers that point to the reading or writing locations within a stream can be
manipulated using the following member functions:
seekg() moves get pointer(input) to a specified location
seekp() moves put pointer (output) to a specified location
tellg() gives the current position of the get pointer
tellp() gives the current position of the put pointer
The other prototype for these functions is:
seekg(offset, refposition );
seekp(offset, refposition );
The parameter offset represents the number of bytes the file pointer is to be moved from the location
specified by the parameter refposition. The refposition takes one of the following three constants
defined in the ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file
example:
file.seekg(-10, ios::cur);
Basic Operation On Text File In C++
File I/O is a five-step process:
1. Include the header file fstream in the program.
2. Declare file stream object.
3. Open the file with the file stream object.
4. Use the file stream object with >>,
cout
fin >> word; count++; } cout
char ch; while(!fin.eof()) { fin.get(ch); fout admno; cout
} }; /* * function to write in a binary file. */ void write_record() { ofstream outFile; outFile.open("student.dat", ios::binary | ios:: app); Student obj; obj.setData(); outFile.write((char*)&obj, sizeof(obj)); outFile.close(); } /* * function to display records of file */ void display() { ifstream inFile; inFile.open("student.dat", ios::binary); Student obj; while(inFile.read((char*)&obj, sizeof(obj))) { obj.showData(); } inFile.close(); } /* * function to search and display from binary file */ void search(int n) { ifstream inFile; inFile.open("student.dat", ios::binary);
Student obj; while(inFile.read((char*)&obj, sizeof(obj))) { if(obj.retAdmno() == n) { obj.showData(); } } inFile.close(); } /* * function to delete a record */ void delete_record(int n) { Student obj; ifstream inFile; inFile.open("student.dat", ios::binary); ofstream outFile; outFile.open("temp.dat", ios::out | ios::binary ); while(inFile.read((char*)&obj, sizeof(obj))) { if(obj.retAdmno() != n) { outFile.write((char*)&obj, sizeof(obj)) ; } } inFile.close(); outFile.close(); remove("student.dat"); rename("temp.dat", "student.dat"); } /* * function to modify a record */ void modify_record(int n) { fstream file; file.open("student.dat",ios::in | ios::out);
Student obj; while(file.read((char*)&obj, sizeof(obj))) { if(obj.retAdmno() == n) { cout
I/O manipulators that take parameters are in the include file.
Default Floating-point Format
• Unless you use I/O manipulators (or their equivalent), the default format for each floating-point number depends on its value.
• No decimal point: 1.0000 prints as 1 • No trailing zeros: 1.5000 prints as 1.5 • Scientific notation for large/small numbers: 1234567890.0 prints as 1.23457e+09
Example
#include #include using namespace std; int main() { const float tenth = 0.1; const float one = 1.0; const float big = 1234567890.0; cout
Following are the standard manipulators normally used in the stream classes:
endl
hex, dec, oct
setbase
setw
setfill
setprecision
ends
ws
flush
setiosflags
resetiosflags
(a) Endl the endl is an output manipulator to generate a carriage return or line feed character. The endl may be used several times in a C++ statement.
For example,
(1)
cout
cout
In addition to the base conversion facilities such as to bases dec, hex and oct, the setbase()manipulator is also used to define the base of the numeral value of a variable. The prototype ofsetbase() manipulator is defined in the iomanip.h header file and it should be include in user program. The hex, dec, oct manipulators change the base of inserted or extracted integral values. The original default for stream input and output is dec.
PROGRAM
A program to show the base of a numeric value of a variable using hex, oct and dec manipulator functions.
/ / using dec, hex, oct manipulator
#include
Void main (void)
{
int value;
cout value;
cout
#include
#include
void main (void)
{
int value
cout value;
cout
void main (void)
{
int a,b;
a = 200;
b = 300;
cout
/ /using setw manipulator
#include
#include
void main (void)
{
int a,b;
a = 200;
b = 300;
cout
A program to illustrate how a character is filled in filled in the unused field width of the value of the data variable.
/ /using setfill manipulator
#include
#include
void main ( void)
{
int a,b;
a = 200;
b = 300;
cout
A program to use the setprecision manipulator function while displaying a floating point value onto the screen.
/ /using setprecision manipulator
#include
#include
void main (void)
{
float a,b,c;
a = 5;
b = 3;
c = a/b;
cout
(f) Ends The ends is a manipulator used to attach a null terminating character (‘\0’) at the end of a string. The ends manipulator takes no argument whenever it is invoked. This causes a null character to the output.
PROGRAM
A program to show how a null character is inserted using ends manipulator while displaying a string onto the screen.
/ /using ends manipulator
#include
#include
Void main ( )
{
int number = 231;
cout
cout
The restiosflags manipulator performs the same function as that of the resetf function. The flags represented by the set bits in f are reset.
The general syntax of the resetiosflags is a follows,
Resetiosflags (long f)
PROGRAM
A program to demonstrate how setiosflags is set while displaying the base of a numeral.
/ /using setiosflags of basefield
#include
#include
void main (void)
{
int value;
cout > value;
cout
hexadecimal = 0xa
octal = 012