Vous êtes sur la page 1sur 20

INHERITANCE

Inheritance is the process by which new classes called


derived classes are created from existing classes called base
classes. The derived classes have all the features of the base
class and the programmer can choose to add new features
specific to the newly created derived class.
Features or Advantages of Inheritance:
Reusability:
Inheritance helps the code to be reused in many situations.
The base class is defined and once it is compiled, it need not
be reworked. Using the concept of inheritance, the
programmer can create as many derived classes from the
base class as needed while adding specific features to each
derived class as needed.
Saves Time and Effort:
The above concept of reusability achieved by inheritance
saves the programmer time and effort. Since the main code
written can be reused in various situations as needed.
Increases Program Structure which results in greater
reliability.
General Format for implementing the concept of
Inheritance:
class derived_classname: access specifier baseclassname
For example, if the base class is exforsys and the derived
class is sample it is specified as:

class sample: public exforsys

If a member or variables defined in a class is private,


then they are accessible by members of the same class
only and cannot be accessed from outside the class.

Public members and variables are accessible from


outside the class.

Protected access specifier is a stage between private


and public. If a member functions or variables defined in
a class are protected, then they cannot be accessed from
outside the class but can be accessed from the derived
class.

Inheritance types
1. Single inheritance:
Only one base class, and one derived class access member
functions, data members from it. and derived class can't
behave again base class.
2. Multilevel inheritance:
eg: base class
l
derived1 class
l
derived2 class
l
derived3 class
.
.
Again derived class acts as another base class

3.Multiple inheritance:
There are two base classes and one derived class which is
derived from both two base classes.
Base1 class base2class
derived class
4. Hierarchical inheritance:
in this one common base class and derived class and from
those another derived classes.
5. Hybrid inheritance:
it is a combination of any above inheritance types.
That is either multiple-multilevel or multiple-hierarchical
MULTIPLE INHERITANCE
Deriving directly from more than one class is usually called
multiple inheritance. Multiple inheritance is an important
feature in C++ and a very good structuring tool.
Friend functions
In principle, private and protected members of a class
cannot be accessed from outside the same class in which
they are declared. However, this rule does not affect friends.
Friends are functions or classes declared with the friend
keyword.
If we want to declare an external function as friend of a
class, thus allowing this function to have access to the
private and protected members of this class, we do it by

declaring a prototype of this external function within the


class, and preceding it with the keyword friend.
Virtual Functions
Virtual, as the name implies, is something that exists in
effect but not in reality. The concept of virtual function is the
same as a function, but it does not really exist although it
appears in needed places in a program.
The
object-oriented
programming
language
C++
implements the concept of virtual function as a simple
member function, like all member functions of the class.
The functionality of virtual functions can be over-ridden in its
derived classes. The programmer must pay attention not to
confuse this concept with function overloading.
Virtual function is a mechanism to implement the concept of
polymorphism (the ability to give different meanings to one
function).
Need for Virtual Function:
The vital reason for having a virtual function is to implement
a different functionality in the derived class.
Properties of Virtual Functions:
Dynamic Binding Property:
Virtual Functions are resolved during run-time or dynamic
binding. Virtual functions are also simple member functions.
The main difference between a non-virtual C++ member
function and a virtual member function is in the way they
are both resolved. A non-virtual C++ member function is
resolved during compile time or static binding. Virtual
Functions are resolved during run-time or dynamic binding

Virtual functions are member functions of a class.


Virtual functions are declared with the keyword
virtual, detailed in an example below.
Virtual function takes a different functionality in the
derived class.

Declaration of Virtual Function:


Virtual functions are member functions declared with the
keyword virtual.
For example, the general syntax to declare a Virtual Function
uses:

class classname //This denotes the base class of C++


virtual function
{
public:
virtual void memberfunctionname() //This denotes the C+
+ virtual function
{
.............
............
}
};

PURE VIRTUAL FUNCTION AND VIRTUAL BASE CLASS


Pure Virtual Function is a Virtual function with no body.
Declaration of Pure Virtual Function:

Since pure virtual function has no body, the programmer


must add the notation =0 for declaration of the pure virtual
function in the base class.
General Syntax of Pure Virtual Function takes the
form:

class classname //This denotes the base class of C++


virtual function
{
public:
virtual void virtualfunctioname() = 0 //This denotes the
pure virtual function in C++
};

VIRTUAL BASE CLASS

class Exforsys
{
protected:
int x;
};
class Exf1:public Exforsys
{ };
class Exf2:public Exforsys
{ };
class Training:public Exf1,public Exf2
{
public:
int example()

{
return x;
}
};
The above program results in a compile time error as the
member function example() of class Training tries to access
member data x of class Exforsys. This results in an error
because the derived classes Exf1 and Exf2 (derived from
base class Exforsys) create copies of Exforsys called
subobjects.
This means that each of the subobjects have Exforsys
member data and member functions and each have one
copy of member data x. When the member function of the
class Training tries to access member data x, confusion
arises as to which of the two copies it must access since it
derived from both derived classes, resulting in a compile
time error.
When this occurs, Virtual base class is used. Both of the
derived classes Exf1 and Exf2 are created as virtual base
classes, meaning they should share a common subobject in
their base class.
For Example:

class Exforsys
{
protected:
int x;
;

class Exf1:virtual public Exforsys


{ };
class Exf2:virtual public Exforsys
{ };
class Training:public Exf1,public Exf2
{
public:
int example()
{
return x;
}
};

POLYMORPHISM
Polymorphism is the ability to use an operator or function in
different ways. Polymorphism gives different meanings or
functions to the operators or functions. Poly, referring to
many, signifies the many uses of these operators and
functions.
A single function usage or an operator functioning in many
ways can be called polymorphism. Polymorphism refers to
codes, operations or objects that behave differently in
different contexts.
Polymorphism is a powerful feature of the object oriented
programming language C++. A single operator + behaves
differently in different contexts such as integer, float or
strings referring the concept of polymorphism. The above
concept leads to operator overloading. The concept of
overloading is also a branch of polymorphism. When the
exiting operator or function operates on new data type it is

overloaded. This feature of polymorphism leads to the


concept of virtual methods.
Polymorphism refers to the ability to call different functions
by using only one type of function call.
In polymorphism, a single function or an operator
functioning in many ways depends upon the usage to
function properly. In order for this to occur, the following
conditions must apply:

All different classes must be derived from a single


base class. In the above example, the shapes of
vehicles (circle, triangle, rectangle) are from the
single base class called Shape.
The member function must be declared virtual in
the base class. In the above example, the member
function for making the vehicle should be made as
virtual to the base class.

Features and Advantages


Polymorphism:

of

the

concept

of

Applications are Easily Extendable:


Once an application is written using the concept of
polymorphism, it can easily be extended, providing new
objects that conform to the original interface. It is
unnecessary to recompile original programs by adding new
types. Only re-linking is necessary to exhibit the new
changes along with the old application. This is the greatest
achievement of C++ object-oriented programming. In
programming language, there has always been a need for
adding and customizing. By utilizing the concept of
polymorphism, time and work effort is reduced in addition to
making future maintenance easier.

Helps in reusability of code.


Provides easier maintenance of applications.

Helps in achieving robustness in applications.

Types of Polymorphism:
C++ provides three different types of polymorphism.

Virtual functions
Function name overloading
Operator overloading

In addition to the above three types of polymorphism, there


exist other kinds of polymorphism:

run-time
compile-time
ad-hoc polymorphism
parametric polymorphism

Other types of polymorphism defined:


run-time:
The run-time polymorphism is implemented with inheritance
and virtual functions.
compile-time:
The compile-time
templates.

polymorphism

is

implemented

with

ad-hoc polymorphism:
If the range of actual types that can be used is finite and the
combinations must be individually specified prior to use, this
is called ad-hoc polymorphism.
parametric polymorphism:
If all code is written without mention of any specific type and
thus can be used transparently with any number of new
types it is called parametric polymorphism.

Concept of Pointers:
Every storage location of memory has an associated
address. Address is a number that grows sequentially. For
every program placed in memory, each variable or function
in the program has an associated address.
The address of operator:
The address of operator or Reference operator is denoted by
the notation &. When the user wants to get the address of a
variable, then the reference operator & can be used. The
operator & is used to find the address associated with a
variable.
The syntax of the reference operator is as follows:
&variablename
This means that the address of the variablename is
achieved.
Example

#include <iostream.h>
void main()
{
int exf=200;
int test=300;
cout<<endl<<&exf
<<endl<<&test;
}

Defining Pointer Variables or Pointer:


In order to define pointer variables, the programmer must
use the operator denoted as * in C++.
The symbol * when placed before a pointer, variable means
that it as a pointer to.
While defining variables, the data type is placed before it.
When the programmer wants to define the integer variable i
it is written:
int i;
The compiler must know the type of data the pointer is
pointing to.
To define pointer variable is as follows:
datatype_of_ variable_pointedto* pointer_varaible;
For example:
char* ch;
This defines that ch is a pointer variable which points to char
data type.
int* i;
This defines that i is a pointer variable which points to int
data type.
float* f;

This defines that f is a pointer variable which points to float


data type.
Pointer to Void
General Syntax:
void* pointer_variable;
Void is used as a keyword.
Referring back to pointer definitions and usage, it is known
that the data type the pointer variable defines is the same
as the data type the pointer points to. The address placed in
a pointer must have the same type as the pointer.
NULL Pointer:
The concept of NULL pointer is different from the above
concept of void pointer. NULL pointer is a type of pointer of
any data type and generally takes a value as zero. This is,
however, not mandatory. This denotes that NULL pointer
does not point to any valid memory address.
The difference
pointers:

between

void

pointers

and

NULL

A Void pointer is a special type of pointer of void and


denotes that it can point to any data type. NULL pointers can
take any pointer type, but do not point to any valid
reference or memory address. It is important to note that a
NULL pointer is different from a pointer that is not initialized.
Memory management operators

There are two types of memory management operators in


C++:

new
delete

These two memory management operators are used for


allocating and freeing memory blocks in efficient and
convenient ways.
New operator:
The new operator in C++ is used for dynamic storage
allocation. This operator can be used to create object of any
type.
General syntax of new operator in C++:
The general syntax of new operator in C++ is as follows:
pointer variable = new datatype;
delete operator:
The delete operator in C++ is used for releasing memory
space when the object is no longer needed. Once a new
operator is used, it is efficient to use the corresponding
delete operator for release of memory.
General syntax of delete operator in C++:
The general syntax of delete operator in C++ is as follows:
delete pointer variable;

In the above example, delete is a keyword and the pointer


variable is the pointer that points to the objects already
created in the new operator

MANIPULATING STRINGS

Strings, or sequences of characters, are represented as


arrays of char elements. For example, when a programmer
wants to represent a char array Exforsys having 30 elements
it is declared:
char sys[30];
This means the character array has 30 storage location
allocated where it can store up to a maximum of 30
characters.
End String Notation
The character array can store the specified maximum of
array limit. This means it can store less than the allocated
array limit up to the maximum. It is essential that a notation
exist to mark the end of character array or string
representation. This end of character array is denoted using
backslash zero \0.
The Differences Between Character Constants and String
Literal:
Initializing Char array
This initialization of char array can be performed using two
methods:

Character representation
String Literals

Represent array of Strings:


It is possible to declare two-dimensional arrays in character
arrays or array of strings.
The general syntax is as follows:
char arrayname[numb1][numb2];
In this numb1 denotes the number of string literals defined
in the array and numb2 defines the maximum length of
characters of the strings.
EXCEPTION HANDLING
Exceptions are run-time anomalies, such as division by zero,
that require immediate handling when encountered by your
program. The C++ language provides built-in support for
raising and handling exceptions.
With C++ exception handling, your program can
communicate unexpected events to a higher execution
context that is better able to recover from such abnormal
events. These exceptions are handled by code that is outside
the normal flow of control.
Exceptions provide a way to react to exceptional
circumstances (like runtime errors) in our program by
transferring control to special functions called handlers.
To catch exceptions we must place a portion of code under
exception inspection. This is done by enclosing that portion
of code in a try block. When an exceptional circumstance
arises within that block, an exception is thrown that

transfers the control to the exception handler. If no


exception is thrown, the code continues normally and all
handlers are ignored.
A exception is thrown by using the throw keyword from
inside the try block. Exception handlers are declared with
the keyword catch, which must be placed immediately after
the try block:
The exception handler is declared with the catch keyword. it
follows immediately the closing brace of the try block. The
catch format is similar to a regular function that always has
at least one parameter. The type of this parameter is very
important, since the type of the argument passed by the
throw expression is checked against it, and only in the case
they match, the exception is caught.
We can chain multiple handlers (catch expressions), each
one with a different parameter type. Only the handler that
matches its type with the argument specified in the throw
statement is executed.
Function templates
Function templates are special functions that can operate
with generic types. This allows us to create a function
template whose functionality can be adapted to more than
one type or class without repeating the entire code for each
type.
In C++ this can be achieved using template parameters. A
template parameter is a special kind of parameter that can
be used to pass a type as argument: just like regular
function parameters can be used to pass values to a
function, template parameters allow to pass also types to a
function. These function templates can use these parameters
as if they were any other regular type.

The format for declaring function templates with type


parameters is:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
The only difference between both prototypes is the use of
either the keyword class or the keyword typename. Its use
is indistinct, since both expressions have exactly the same
meaning and behave exactly the same way.
Class templates
We also have the possibility to write class templates, so that
a class can have members that use template parameters as
types
FILE HANDLING
C++ provides the following classes to perform output and
input of characters to/from files:
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.
These classes are derived directly or indirectly from the
classes istream, and ostream. We have already used objects
whose types were these classes: cin is an object of class
istream and cout is an object of class ostream.
we can use our file streams the same way we are already
used to use cin and cout, with the only difference that we
have to associate these streams with physical files.

Open a file
The first operation generally performed on an object of one
of these classes is to associate it to a real file. This
procedure is known as to open a file.
An open file is represented within a program by a stream
object these classes, in the previous example this was
myfile) and any input or output operation performed on this
stream object will be applied to the physical file associated
to it.
In order to open a file with a stream object we use its
member function open():
open (filename, mode);
Where filename is a null-terminated character sequence of
type const char * (the same type that string literals have)
representing the name of the file to be opened, and mode is
an optional parameter with a combination of the flags.
Closing a file
When we are finished with our input and output operations
on a file we shall close it so that its resources become
available again. In order to do that we have to call the
stream's member function close().
This member function takes no parameters, and what it does
is to flush the associated buffers and close the file.
Once this member function is called, the stream object can
be used to open another file, and the file is available again
to be opened by other processes.
In case that an object is destructed while still associated

with an open file, the destructor automatically calls the


member function close().
tellg() and tellp()
These two member functions have no parameters and return
a value of the member type pos_type, which is an integer
data type representing the current position of the get stream
pointer (in the case of tellg) or the put stream pointer (in
the case of tellp).
seekg() and seekp()
These functions allow us to change the position of the get
and put stream pointers. Both functions are overloaded with
two different prototypes. The first prototype is:
seekg ( position );
seekp ( position );
Using this prototype the stream pointer is changed to the
absolute position position (counting from the beginning of
the file). The type for this parameter is the same as the one
returned by functions tellg and tellp: the member type
pos_type, which is an integer value.
The other prototype for these functions is:
seekg ( offset, direction );
seekp ( offset, direction );

Vous aimerez peut-être aussi