Pure Virtual Function
Pure Virtual Function
Pure Virtual Function
Introduction
• A pure virtual function is a virtual function in
C++ for which we need not to write any
function definition and only we have to
declare it. It is declared by assigning 0 in the
declaration.
• An abstract class is a class in C++ which have at least
one pure virtual function.
• Abstract class can have normal functions and
variables along with a pure virtual function.
• Abstract class cannot be instantiated, but pointers
and references of Abstract class type can be created.
• Abstract classes are mainly used for Upcasting, so
that its derived classes can use its interface.
• If an Abstract Class has derived class, they must
implement all pure virtual functions, or else they will
become Abstract too.
#include<iostream>
using namespace std;
class B
{
public:
virtual void s() = 0; // Pure Virtual Function
};
class D:public B
{ public: void s()
{
cout << "Virtual Function in Derived class\n";
}
};
int main()
{
B *b;
D dobj;
b = &dobj;
b->s();
}
Virtual Function
• Virtual functions in C++ use to create a list of base class
pointers and call methods of any of the derived classes
without even knowing the kind of derived class object.
Virtual functions are resolved late, at the runtime.
• If A virtual function in a base class declared as once a
member function, it becomes virtual in every class
derived from that base class. So, use of the keyword
virtual is not necessary in the derived class while
declaring redefined versions of the virtual base class
function.
#include<iostream>
using namespace std;
class B
{
public:
virtual void s()
{
cout<<" In Base \n";
}
};
class D: public B
{
public:
void s()
{
cout<<"In Derived \n";
}
};
int main(void)
{
D d; // An object of class D
B *b= &d; // A pointer of type B* pointing to d
b->s(); // prints"D::s() called"
return 0;
}
OUTPUT:
In Base
In Derived
Abstract class
• An abstract class in C++ is a class that has at
least one pure virtual function (i.e., a function
that has no definition). The classes inheriting
the abstract class must provide a definition for
the pure virtual function; otherwise, the
subclass would become an abstract class itself.
• Abstract classes are essential to providing an
abstraction to the code to make it reusable
and extendable. For example, a Vehicle parent
class with Truck and Motorbike inheriting from
it is an abstraction that easily allows more
vehicles to be added. However, even though
all vehicles have wheels, not all vehicles have
the same number of wheels – this is where a
pure virtual function is needed.
Example
#include<iostream>
using namespace std;
class Shape
{ public:
virtual int Area() = 0; // Pure virtual function is declared as follows. // Function to set width.
void setWidth(int w)
{
width = w;
} // Function to set height.
void setHeight(int h)
{
height = h;
}
protected:
int width; int height;
}; // A rectangle is a shape; it inherits shape.
class Rectangle: public Shape
{
public: // The implementation for Area is specific to a rectangle.
int Area()
{
return (width * height);
}
}; // A triangle is a shape too; it inherits shape.
class Triangle: public Shape
{ public: // Triangle uses the same Area function but implements it to // return the area of a triangle.
int Area()
{
return (width * height)/2;
} };
int main()
{
Rectangle R;
Triangle T;
R.setWidth(5); R.setHeight(10); T.setWidth(20); T.setHeight(8); cout << "The area of the rectangle is: " << R.Area() << endl; cout << "The area of the triangle is: " << T.Area() << endl; }
Similarities between virtual function and pure
virtual function
• These are the concepts of Run-time
polymorphism.
• Prototype i.e. Declaration of both the
functions remains the same throughout the
program.
• These functions can’t be global or static.
Difference between virtual function and
pure virtual function in C++
Virtual function Pure virtual function
Classes having virtual functions are not Base class containing pure virtual function
abstract. becomes abstract.
Syntax:
virtual<func_type><func_name>()
Syntax:virtual<func_type><func_name>()
{ = 0;
// code
}
<iostream>
This file defines the cin, cout, cerr and clog objects, which correspond to
1 the standard input stream, the standard output stream, the un-buffered
standard error stream and the buffered standard error stream,
respectively.
<iomanip>
2 This file declares services useful for performing formatted I/O with so-
called parameterized stream manipulators, such as setw and setprecision.
<fstream>
3
This file declares services for user-controlled file processing.
The Standard Output Stream (cout)
The predefined object cout is an instance of ostream class.
The cout object is said to be "connected to" the standard
output device, which usually is the display screen. The cout is
used in conjunction with the stream insertion operator,
which is written as << which are two less than signs
#include <iostream>
using namespace std; Output: Value of str is:
Hello C++
int main()
{
char str[] = "Hello C++";
cout << "Value of str is : " << str << endl; -printf(“Hello”);
}
The Standard Input Stream (cin)
• The predefined object cin is an instance of istream class. The cin object is
said to be attached to the standard input device, which usually is the
keyboard. The cin is used in conjunction with the stream extraction
operator, which is written as >> which are two greater than signs
#include <iostream>
using namespace std;
int main()
{
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
}
Output:
Please enter your name:
Keerthi
Your name is: Keerthi
The Standard Error Stream (cerr)
• The predefined object cerr is an instance of ostream class. The cerr
object is said to be attached to the standard error device, which is
also a display screen but the object cerr is un-buffered and each
stream insertion to cerr causes its output to appear immediately.
• The cerr is also used in conjunction with the stream insertion
operator
#include <iostream>
using namespace std;
int main()
{
char str[] = "Unable to read....";
cerr << "Error message : " << str << endl;
}
Output:
Error message : Unable to read....
The Standard Log Stream (clog)
• The predefined object clog is an instance of ostream class. The clog
object is said to be attached to the standard error device, which is
also a display screen but the object clog is buffered. This means that
each insertion to clog could cause its output to be held in a buffer
until the buffer is filled or until the buffer is flushed.
• The clog is also used in conjunction with the stream insertion
operator
#include <iostream>
using namespace std;
int main()
{
char str[] = "Unable to read....";
clog << "Error message : " << str << endl;
}
Output:
Error message: Unable to read
I/O refers to the input - output functions in C
language.
High level I/O
These are easily understood by human beings
The advantage is portability.
Low level I/O
These are easily understood by computer.
The advantage is that execution time is less.
The disadvantage is that Non portability.
cerr clog
Function Description
fprintf ( ) write data into a file
fscanf ( ) read data from a file
putc ( )/ fputc() write a character into a file
getc ( ) /fgetc() read a character from a file
putw ( ) write a number into a file
getw ( ) read number from a file
fputs ( ) write a string into a file
fgets ( ) read a string from a file
fread() read an entire record from a file
fwrite() write an entire record into a file
Stream classes hierarchy
ios class is topmost class in the stream classes
hierarchy. It is the base class for istream,
ostream, and streambuf class.
istream and ostream serves the base classes for
iostream class. The class istream is used for
input and ostream for the output.
Class ios is indirectly inherited to iostream class
using istream and ostream. To avoid the
duplicity of data and member functions of ios
class, it is declared as virtual base class when
inheriting in istream and ostream
class istream: virtual public ios
{
};
class ostream: virtual public ios
{
};
int main()
{
A a;
a.fun();
return 0;
}
// C++ program to show that scope resolution operator :: is used
// to define a function outside a class
#include<iostream>
using namespace std;
class A
{
public:
// Only declaration
void fun_y();
};
// Definition outside class using ::
void A::fun_y()
{
cout << "fun_y() called";
}
int main()
{
A a;
a.fun_y();
return 0;
}
// Use of scope resolution operator in multiple inheritance.
#include<iostream>
using namespace std;
class A
{
protected:
int x;
public:
A() { x = 10; }
};
class B
{
protected:
int x;
public:
B() { x = 20; }
};
class C: public A, public B
{
public:
void fun()
{
cout << "A's x is " << A::x;
cout << "\nB's x is " << B::x;
}
};
int main()
{
C c;
c.fun();
return 0;
}
Output:A's x is 10 B's x is 20
Stream IO
• 1.1 Streams
C/C++ IO are based on streams, which are sequence of
bytes flowing in and out of the programs (just like water
and oil flowing through a pipe). In input operations, data
bytes flow from an input source (such as keyboard, file,
network or another program) into the program. In output
operations, data bytes flow from the program to an
output sink (such as console, file, network or another
program). Streams acts as an intermediaries between the
programs and the actual IO devices, in such the way that
frees the programmers from handling the actual devices,
so as to archive device independent IO operations.
• C++ provides both the formatted and
unformatted IO functions. In formatted or
high-level IO, bytes are grouped and
converted to types such as int, double, string
or user-defined types. In unformatted or low-
level IO, bytes are treated as raw bytes and
unconverted. Formatted IO operations are
supported via overloading the stream
insertion (<<) and stream extraction (>>)
operators, which presents a consistent public
IO interface.
To perform input and output, a C++ program:
• Construct a stream object.
• Connect (Associate) the stream object to an actual
IO device (e.g., keyboard, console, file, network,
another program).
• Perform input/output operations on the stream,
via the functions defined in the stream's pubic
interface in a device independent manner. Some
functions convert the data between the external
format and internal format (formatted IO); while
other does not (unformatted or binary IO).
• Disconnect (Dissociate) the stream to the actual IO
device (e.g., close the file).
• Free the stream object.
Stringstream in C++
int count = 0;
while (s >> word)
count++;
return count;
}
// Driver code
int main()
{
string s = "geeks for geeks geeks “;
cout << " Number of words are: " << countWords(s);
return 0;
}
• OUTPUT:
Input : geeks for geeks geeks
Output : Number of words are: 4
C++ FileStream example: writing to a file
int i;
fp = fopen("GeeksForGeeks.TXT", "w");
if (fp == NULL) {
printf("\n The file could "
"not be opened");
exit(1);
}
char c;
fp = fopen("file.txt", "w");
c = fgetc(fp);
if (ferror(fp)) {
printf("Error in reading from"
" file : file.txt\n");
}
clearerr(fp);
if (ferror(fp)) {
printf("Error in reading from "
"file : file.txt\n");
}
// Driver Code
int main()
{
FILE* fp;
if (fp == NULL) {
perror("Error: ");
return (-1);
}
return (0);
}
Formatted I/O
void IOS_setf()
{
cout << "\n--------------------------\n";
cout << "Implementing ios::setf\n\n";
int val1=100,val2=200;
cout.setf(ios::showpos);
cout<<val1<<" "<<val2;
cout << "\n--------------------------\n";
}
void IOS_unsetf()
{
cout << "\n--------------------------\n";
cout << "Implementing ios::unsetf\n\n";
cout.setf(ios::showpos|ios::showpoint);
// Clear the showflag flag without
// affecting the showpoint flag
cout.unsetf(ios::showpos);
cout<<200.0;
cout << "\n--------------------------\n";
}
// Driver Method
int main()
{
IOS_width();
IOS_precision;
IOS_fill();
IOS_setf();
IOS_unsetf();
return 0;
}
Formatting using Manipulators
The second way you can alter the format
parameters of a stream is through the use of
special functions called manipulators that can be
included in an I/O expression.
UNIT - 5
• Exception Handling:
Benefits of exception handling
Throwing an exception
The try Block
Catching an exception
Exception objects
Exception specification
Stack unwinding
Rethrowing an exception
Catching all exception
Exception Handling
Exceptions are run-time anomalies or abnormal conditions
that a program encounters during its execution. There are
two types of exceptions: a)Synchronous,
b)Asynchronous(Ex:which are beyond the program’s control,
Disc failure etc). C++ provides following specialized
keywords for this purpose.
try: represents a block of code that can throw an exception.
catch: represents a block of code that is executed when a
particular exception is thrown.
throw: Used to throw an exception. Also used to list the
exceptions that a function throws, but doesn’t handle itself.
Why Exception Handling?
Following are main advantages of exception
handling over traditional error handling:
1) Separation of Error Handling code from
Normal Code
2) Functions/Methods can handle any exceptions
they choose
3) Grouping of Error Types
Benefits of exception handling
// Some code
cout << "Before try \n";
try {
cout << "Inside try \n";
if (x < 0)
{
throw x;
cout << "After throw (Never executed) \n";
}
}
catch (int x ) {
cout << "Exception Caught \n";
}
// Driver Code
int main()
{
f3();
getchar();
return 0;
}
Rethrowing an exception
Rethrowing an expression from within an
exception handler can be done by calling throw,
by itself, with no exception. This causes current
exception to be passed on to an outer try/catch
sequence. An exception can only be rethrown
from within a catch block. When an exception is
rethrown, it is propagated outward to the next
catch block.
Example
• #include<iostream>
using namespace std;
void sub(int i,int j)
{
try
{
if(i==0)
{
throw i;
}
else
cout<<“Subtraction result is: “<<i-j<<endl;
}
catch(int i)
{
cout<<“Exception caught inside sub()\n”;
throw;
}
};
int main()
{
try
{
sub(8,4);
sub(0,8);
}
catch(int k)
{
cout<<“Exception caught inside main()\n”;
}
return 0;
}
• OUTPUT:
• Subtraction result is: 4
Exception caught inside sub()
Exception caught inside main()
Catching all exceptions
• Exceptions are the problems which arise at the
time of execution of program. It is an event which
is thrown at runtime. It protects the code and run
the program even after throwing an exception.
Exception handling is used to handle the
exceptions. We can use try catch block to protect
the code.
• Catch block is used to catch all types of exception.
The keyword “catch” is used to catch exceptions.
#include <iostream>
using namespace std;
void func(int a)
{
try
{
if(a==0) throw 23.33;
if(a==1) throw 's';
}
catch(...)
{
cout << "Caught Exception!\n";
}
}
int main()
{
func(0);
func(1);
return 0;
}
Output:
Caught Exception!
Caught Exception!