Vous êtes sur la page 1sur 32

Inheritance

Making a private member inheritable


What we do if the private data needs to be inherited by a derived class?
Modifying the visibility limit of the private member by making it public.
This would make it accessible to all other functions of the program.
C++ provides a third visibility modifier, protected.
A member declared as protected is accessible by the member functions within its
class and any class which is immediately derived from it.
class alpha{
private:
.
// visible to member functions within its class.
Protected: // visible to member functions of its own and derived classes.

.
Public:
// visible to all functions in the program.
};

Inheritance
When a protected member is inherited in the public mode, it becomes
protected in the derived class too and therefore is accessible by the member
functions of the derived class.
It is also ready for further inheritance.
A protected member derived in the private mode becomes private in the derived
class.
It is available for member functions of the derived class it is not available for
further inheritance.
The keywords private, public and protected may appear in any order and any
number of times in the declaration of the class.
It is possible to inherit a base class in protected mode.
Both the public and protected members of the base class will be protected
members of the derived class.

Inheritance
Effect of inheritance on the visibility of members

Inheritance
Visibility of inherited members

Inheritance
Multi level inheritance

Class A serves as the base class for the


derived class B, which in turn serves as a base
class for the derived class C.
Class B is known as intermediate base class.
The chain ABC is known as inheritance
path.

A derived class with multi level inheritance is declared as follows


class A {};
class B : public A {.};
class C : public B {.};
This process can be extended to any number of levels.

Inheritance
//muti level inheritance
#include <iostream>
using namespace std;
class student {
protected:
int roll_no;
public:
void get_no(int);
void put_no(void);
};
void student :: get_no(int a){
roll_no =a;
}
void student :: put_no(){
cout << "Roll Number " << roll_no << "\n";
}

Inheritance
class test : public student{ // first level derivation
protected :
float sub1;
float sub2;
public:
void get_marks(float,float);
void put_marks(void);
};
void test :: get_marks(float x, float y){
sub1= x;
sub2= y;
}
void test :: put_marks(){
cout << "Mark in sub1 : " << sub1 << "\n";
cout << "Mark in sub2 : " << sub2 << "\n";
}

Inheritance
class result : public test {
//second level derivation
float total;
public:
void display (void);
};
void result :: display(void){
total= sub1+sub2;
put_no();
put_marks();
cout << "Total : " << total << "\n";
}
int main(){
result student1;
student1.get_no(111);
student1.get_marks(75.5, 80.5);
student1.display();
system("pause");
return 0;
}

Inheritance
Multiple inheritance
A class can inherit two or more classes.
Allows us to combine the features of
several existing classes as a starting point
for new classes.
The syntax of a derived class with multiple base
class
class : visibility B-1, visibility B-2 .
{
. // Function body
}
Visibility may be either private or public. The base classes may be separated by commas.

Inheritance
#include <iostream>
using namespace std;
class M {
protected:
int m;
public:
void get_m(int);
};
class N {
protected:
int n;
public:
void get_n(int);
};
class P : public M , public N{
public:
void display (void);
};

Inheritance
void M :: get_m(int x){
m=x;
}
void N :: get_n(int y){
n=y;
}
void P :: display (void){
cout << " m = " << m << "\n";
cout << " n = " << n << "\n";
cout << " m*n = " << m*n << "\n";
}
int main(){
P p;
p.get_m(10);
p.get_n(20);
p.display();
system("pause");
return 0;
}

Polymorphism
Polymorphism means one name multiple forms.
Concept of Polymorphism is implemented using the overloaded functions and
operators.
The overloaded member functions are selected for invoking by matching
arguments ,both type and number.
This information is known to the compiler at the compile time and compiler is
able to select the appropriate function for a particular call at the compile
time
itself.
This is called early binding or static binding also known as compile time
polymorphism.
Let us consider a situation where the function name and prototype is the same in
both the base and derived classes.
We may use the class resolution operator to specify the class while invoking the
functions with the derived class objects.
It would be nice if the appropriate member function could be selected while the
program is running. This is known as run time polymorphism.
C++ supports a mechanism known as virtual function to achieve run time
polymorphism.

Polymorphism

Achieving polymorphism

Virtual functions
When we use the same function name both in the base and derived classes, the
function in base class is declared as virtual using the keyword virtual
preceding its normal declaration .
When a function is made virtual, C++ determines which function to be used at
run time based on the type of object pointed to by the base pointer,
rather
than by the type of the pointer.
Thus by making the base pointer to point to different objects we can execute
different versions of virtual function.
class Shape {
protected:
int width, height;
public: Shape( int a=0, int b=0) { width = a; height = b; }
// pure virtual function
virtual int area() = 0;
};
The = 0 tells the compiler that the function has no body and above virtual
function will be called pure virtual function.

Data file operations


Data file operations
A file is a collection of related data stored in a particular area on the disk.
Programs can be designed to perform the read and write operations on these
files.
A program typically involves either or both of the following kinds of data
communication.
Data transfer between the console unit and the program.
Data transfer between the program and a disk file.

Data file operations


Data file operations
The I/O system of C++ handles file operations which is very similar to console
input and output operation.
It uses file streams as the interface between the programs and files.
The stream that supplies data to the program is known as input stream and the
one that receives data from the program is known as output stream.

File input and output streams


The input operation involves the creation of the input stream and linking with
the program and the input file.
The output operation involves establishing an output stream with necessary
links with the program and the output file.

Data file operations


Classes for file stream operations
The I/O system of C++ contains a set of classes such as ifstream, ofstream,
fstream.
These streams are derived from fstreambase and from the corresponding
iostream class
These classes are declared in fstream and therefore we must include this file in
any program that uses files.

Stream classes for file operations

Data file operations


Classes for file stream operations
filebuf its purpose is to set the file buffers to read and write.
fstreambase provides operations common to the file streams.
ifstream provides input operations.
ofstream provides output operations
fstream - provides support for simultaneous input and output operations.
Opening and closing file
If we want to use a file , we need to decide the following things about the file
and its following use
1.Suitable name for the file
2.Data type and structure
3.Purpose
4.Opening method
File name is a string of characters that make up a valid file name for the OS.
It may contain two parts, a primary name and an optional period with extension
eg. Test.doc,input.data

Data file operations


For opening a file we must first create a file stream and then link it to the
filename.
File stream can be defined using the classes ifstream, ofstream and fstream that
are contained in the header file fstream.
A file is opened in two ways
1.Using the constructor function of the class. only one file
2.Using the member function open() of the class. multiple files.
Opening the file using constructor
A file name is used to initialize the file stream object
1.Create the file stream object to manage the stream using appropriate class.
2.Initialize the file object with the desired filename.
eg. ofstream outfile(Result); \\ output only
This creates outfile as the ofstream object. This statement also opens the file
result and attaches it to the ouput stream outfile.
Similarly ifstream infile (data);

Data file operations

Two file streams working on different files.

We can use same file name for both


reading and writing data.
Program1
..
ofstream outfile(salary);
.
Program2
..
ifstream infile(salary);
.

Two file streams working on one file.


The connection with a file is closed automatically when the stream object expires.

Data file operations


We can use a single program to do operations on a file.

outfile.close();
ifstream infile (salary);

.
infile.close();
ofstream outfile (salary);

Data file operations


//creating files with constructor functions
#include <iostream>
#include <fstream>
int main(){
ofstream outf("item");
cout << "enter item name : " << "\n" ;
char name[30];
cin >> name;
outf << name << "\n";
cout << "enter item cost : " << "\n" ;
float cost;
cin >> cost;
outf << cost << "\n";
outf.close();

Data file operations


ifstream inf ("item");
inf >> name;
inf >> cost;
cout<< "\n\n";
cout << "item name : "<< name <<"\n";
cout << "item cost : "<< cost <<"\n";
inf.close();
system ("pause");
return 0;
}

Data file operations


Opening files using open()
The function open() can open multiple files that use the same stream object.
Detecting end of file
Detection of end of file condition is necessary for preventing any further attempt
to read data from the file
while (fin)
An ifstream object , such as fin, returns a value of zero if any error occurs in the
file operation including the end of file condition.

Exception handling
It is very rare that a program works for the first time. It will have bugs
Two common bugs are logic errors and syntactic errors.
We come across some errors other than logic and syntax. They are known as
exceptions(run time anomalies or unusual conditions).
Conditions such as 1. divide by zero 2.access to an array outside its bounds
3.Running out of memory or disk space.
Basics of exception handling - two types of Exceptions
1.Synchronous out of range index ,over flow
2.Asynchronous events beyond the control of the program(keyboard interrupt)
Exception handling mechanism is to provide means to detect and report an
exceptional circumstance
The mechanism suggests a separate error handing code that performs the
following tasks.
1.Find the problem (hit the exception)
2.Inform that an error had occurred (throw an exception)
3.Receive the error information (catch the exception)
4.Take corrective actions (handle exception)

Exception handling
Exception handling mechanism
Basically built upon 3 keywords
Try, throw, catch
Keyword try is used to preface a block of
Statements Which may generate exceptions.
(try block)

When an exception is detected it is thrown using


a Throw statement in the try block.

Catch, catches the exception thrown by the throw


statement in the try block.

Exception handling
Exception handling mechanism

When try block throws an exception, the program control leaves the try block and
enters the catch statement of the catch block.
Exceptions are objects used to transmit information about a problem.
If the type of object thrown matches the arg type in the catch statement, then
catch block is executed for handling the exception.
If they do not match, the program is aborted with the help of abort() function
which is invoked by default.
When no exception is detected and thrown, control goes to the statement
immediately after the catch block.

Exception handling
// TRY BLOCK THROWING AN EXCEPTION
#include <iostream>
using namespace std;
int main(){
int a,b;
cout << "Enter the values of a & b :" << "\n";
cin >> a ;
cin >> b;
int x = a-b;
try {
if (x !=0){
cout << "Result a/x :" << a/x;}
else
{
throw(x);
}
}

Exception handling
catch (int i){
cout << "Exception caught : x = " << x << "\n";
}
cout << "end";
system ("pause");
return 0;
}
Exceptions are thrown by functions which are invoked from within the try block.
The point at which throw is executed is called throw point.
Once the exception is thrown to the catch block, control cannot return to the throw
point.

Exception handling

Function invoked by try block showing exception.


Try block is followed by the catch block , irrespective of the location of the throw
point.

Exception handling
Throwing mechanism
when an exception that is desired to be handled is detected , it is thrown using
the throw statement.
throw (exception);
throw exception;
throw; // used for rethrowing an exception
The operand object exception may be of any type, including constants. It is also
possible to throw objects not intended for error handling.
Catching mechanism
Code for exception is handled in catch block.
catch (type arg) {
// statements for managing exception
}
The type indicates the type of exception that catch block handles.
The parameter arg is an optional parameter name.
The catch statement catches an exception whose type matches with the type of
catch argument .
Due to mismatch, if an exception is not caught, abnormal program termination

Exception handling
Multiple catch statement
Program segment has more than one condition to throw exception.
We can associate more than one catch statement with a try.
try {
// try block
When an exception is thrown, exception handlers are
}
searched in an order for an appropriate match.
catch (type1 arg){
// catch block1
The first handler that yields a match is executed.
}
After executing the handler the control goes to the first
catch (type2 arg){
Statement after the last catch block for that try.
// catch block2
}
.
.
catch (typeN arg){
// catch block N
}

Vous aimerez peut-être aussi