You are on page 1of 35

Paper Code: BCA 209

Paper ID: 20209


Paper: Object Oriented Programming using C++
UNIT I
Introduction: Introducing Object-Oriented Approach, Relating to other paradigms (functional,
data decomposition). Features of Procedure oriented programming, Basic Concepts of Object
Oriented Programming, Benefits of OOP, Applications of OOP, Difference between C and C++,
cin, cout, new, delete operators.
C++ Environment: Program development environment, the language and the C++ language
standards. C++ standard libraries.
Introduction to various C++ compilers, C++ standard libraries, Testing the C++ program in
Turbo C++/Borland C++/ MicroSoft VC++/GNU C++ compiler. [T1][T2][T3]
[No. of Hrs: 12]
UNIT II
Classes and Objects: Encapsulation, information hiding, abstract data types, Object & classes,
attributes, methods, C++ class declaration, references, this pointer, Function Overloading,
Constructors and destructors, instantiation of objects, Default parameter value, C++ garbage
collection, dynamic memory allocation, Meta class/abstract classes.[T1][T2]
[No. of Hrs. 12]
UNIT III
Inheritance and Polymorphism: Inheritance, Class hierarchy, derivation public, private &
protected, Aggregation,
composition v/s classification hierarchies, Polymorphism,
Categorization of polymorphism techniques, Method polymorphism, Polymorphism by
parameter, Operator overloading, Parametric polymorphism, Virtual Function, Early v/s Late
Binding.[T1][R2]
[No. of Hrs: 10]
UNIT IV
Generic Programming Introduction, templates, template functions, Overloading of template
functions, Overriding inheritance methods.
Files and Exception Handling: Persistent objects, Streams and files, Namespaces, The basic
stream classes: C++ predefined streams, Error handling during file operations, Command Line
Arguments. Types of Exception, Catching and Handling Exceptions.[T1][T3]
[No. of Hrs: 10]

Unit-1(Introduction)
Introduction to the Object-oriented Approach
The fundamental idea behind an object-oriented language is to combine both data and the
functions that operate on the data into a single unit. Such a unit is called an object.
Data members of an object can be accessed only by using the functions of the object. Therefore,
the data is hidden and is safe from accidental alteration. Data and functions are stored into a
single entity.
The functions of an object are called the member functions. These member functions are called
method in other object-oriented languages like Small Talk.
Figure shows the components of an object in C++.

Components of an Object

Relating To Other paradigms


The important elements of an object-oriented language are:
Class
An Object in C++ is an instance of a class. For example, in the following statement:
int iNum1, iNum2, iNum3;
iNum1, iNum2, iNum3 are three variables of type int.
Similarly, We can define many objects of the same class as shown in Figure

Class and Objects of the Class

Inheritance
Inheritance is the process of creating a new class, called the derived class, from the existing
class, called the base class.
Figure shows the inheritance of a derived class from the base class.

Figure ;- Inheritance of a Derived Class From a Base Class

For example, motorcycles, cars and trucks have certain common properties-- all have wheels,
engines and breaks. Therefore, they can be grouped under a class called automobiles. Apart from
sharing these common features, each subclass has its own particular characteristics--cars use
petrol while trucks use diesel.
The derived class has its own characteristics and, in addition, inherits the properties of the base
class.
Reusability
The concept of inheritance provides an important feature to the object-oriented languagereusability. A programmer can take an existing class and, without modifying it, and additional
features and capabilities to it. This is done by deriving a new class from an existing class.

Polymorphism
The word polymorphism is derived from two Latin words poly (many) and morphs
(forms). The concept of using operators or functions in different ways, depending on what they
are operating on, is called polymorphism.
Object Oriented Programming (OOP) is a programming paradigm that uses "objects" and
their interactions to design applications and computer programs. It is based on several
techniques, including encapsulation, modularity, polymorphism, and inheritance.
Inheritance : Subclasses are more specialized versions of a class, which inherit attributes and
behaviors from their parent classes, and can introduce their own. Inheritance is inheriting a class
into another class.
Encapsulation : Encapsulation conceals the functional details of a class from objects that send
messages to it. This is hiding the internal details.
Abstraction : Abstraction is simplifying complex reality by modelling classes appropriate to the
problem, and working at the most appropriate level of inheritance for a given aspect of the
problem. Building class is an abstraction process.
Polymorphism : Multiple objects exhibiting similar features in different ways is known as
polymorphism. Polymorphism is the process of using an operator or function in different ways
for different set of inputs given.
Features of Procedure oriented programming:1) Emphasis is on doing things (algorithms).
2) Large programs are divided into smaller programs known as functions.
3) Most of the functions share global data.
4) Data more openly around the system from function to function.
5) Functions transform data from one form to another.
6) Employs top-down approach in program design.

Basic Concept of Object Oriented Programming (Features):


1. Objects:
Objects are the basic run time entities. This represents a person, a place, a bank A/C or
any item that the program has to handle. They can represent user define data type.
Programming problem is analysis I term of object and the nature of communication
between them. Objects represents space in the memory and have an associate address like
one record or structure in C. When a program is executed the objects interacts by
sending massages to one another each object contains data & code to manipulate the data.

Object: Student
Data: Name
Date Of
Birth
Marks
Functions: Total
Average
Display

2. Classes:
The entire set of data & code of an object can be made a user define data type with the
help of a class. Objects are variables of the class. Once the class has been define we can
create any number of objects belong to that class. A class is a collection of objects of
similar type.
3. Data abstraction & encapsulation
The wrapping of data & functions into a single unique class is known as encapsulation.
The data is hidden from outside functions, only those functions which are included in the
class can access it. This feature is called data hiding or information hiding.
Abstraction refers to the act of representing essential features without including the
background details. Classes use the concept of abstraction & are defined as a list of
abstract attribute. The attribute are called data members because they hold information &
function that operate on this data are called methods as member functions. Classes are
known as abstract data type.
4. Inheritance
Inheritance is the process by which objects of one class can have properties of objects of
another class. It supports the concept of hierarchical classification. The concept of
inheritance provides the idea of reusability this means that we can add additional features
to an existing class without modifying it. We can drive one class from the existing class
the new class will have combine feature of both the classes.
5. Polymorphism
Polymorphism is Greek term mean the ability to take more than one from.
Ex- For one operator operation ca take different from if operator is working on number
+ than it gives sum of numbers & if this operation is working on string than it will give
concatenation string. This type of behavior is known as operator overloading.

A single function name can used to handle different number & different types of
arguments. Using single function name to perform different type of task is known as
function overloading. In Object Oriented programming language like C++ polymorphism
achieve by operator overloading & function overloading.
6. Dynamic Binding
Binding refers to the linking of a processor call to the code to be executed I response to
the call dynamic binding is known as late binding means that the code associated with a
given procedure call is not known until the time of the call at run time. This is associated
with polymorphism & inheritance.
7. Message Passing
Object oriented program consist of the set of object that communicate with each other
object communicate by sending & receiving information in the form of message.

Benefits Of OOPS:1) through inheritance, we can eliminate redundant code and extend the use of existing classes
which is not possible in procedure oriented approach.
2) We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch which happens procedure
oriented approach. This leads to saving of development time and higher productivity.
3) The principle of data hiding helps the programmer to build secure programs that cannot be
Invaded by code in other parts of the program.
4) It is possible to have multiple instances of object to co-exist without any interference.
5) It is possible to map objects in the problem domain to those in the program.
6) It is easy to partition the work in a project based on objects.
6) The data-centered design approach enables us to capture more details of a model in
implementable from.
7) Object oriented systems can be easily upgraded from small to large systems.
8) Message passing techniques for communication between objects makes the interface
descriptions with external systems much simpler.
9) Software complexity can be easily managed.

Application Of OOPs:OOP Provides Many Applications:1) Real time Systems : A real time system is a system that give output at given instant and its parameters changes at
every time. A real time system is nothing but a dynamic system. Dynamic means the system
that changes every moment based on input to the system. OOP approach is very useful for Real
time system because code changing is very easy in OOP system and it leads toward dynamic
behavior of OOP codes thus more suitable to real time system.
2) Simulation and Modelling: System modelling is another area where criteria for OOP approach is countable. Representing a
system is very easy in OOP approach because OOP codes are very easy to understand and thus
is proffered to represent a system in simpler form.
3) Hypertext And Hypermedia : Hypertext and hypermedia is another area where OOP approach is very useful. Its ease of using
OOP codes that makes it suitable for various media approaches.
4) Decision support system : Decision support system is an example of Real time system that too very advance and complex
system.
5) CAM/CAE/CAD System : Computer has wide use of OOP approach. This is due to time saving in writing OOP codes and
dynamic behaviour of OOP codes.
6) Office Automation System : Automation system is just a part or type of real time system. Embedded systems make it easy to
use OOP for automated system.
7) AI and expert system : It is mixed system having both hypermedia and real time system.

Difference between Procedural and Object Oriented Programming ( C and C++)


We can summarize the differences as follows :
Procedural Programming
top down design
create functions to do small tasks
communicate by parameters and return values
Object Oriented Programming
design and represent objects
determine relationships between objects
determine attributes each object has
determine behaviours each object will respond to
create objects and send messages to them to use or manipulate their attributes

Procedure_Oriented_Programming

Object_Oriented_

(C)

Programming ( C++)

Emphasis is on action rather than data.

Programs are divided into subprograms or


sub procedures.
Data structure are designed for simple data
for simple data type

Functions & data are separate

Data can be access by external function

New data & function for the whole


application cant be easily added when
ever necessary.
Follows up-bottom approach in program
designed

Emphasis is on data rather than


procedures
Programs are divided into
objects.
Data structures are designed
such that they characterized the
objects.
Functions that operate on the
data of an object are typed
together in the data structure.
Data is hidden and cant be
access by external functions.
Objects may communicate with
each their through function.
New data & function can be
easily added when ever
necessary
Follows bottom-up approach in
program designed.

OPERATORS
cin: it is used to give input
cout: used to get output
new: to allocate memory to newly created variable
delete: to deallocate memory already assign to some variable
Program development environment is a software application that provides comprehensive
facilities to computer programmers for software development.

Language and the C++ language standards


Standard Libraries
Standard C++ consists of three important parts:

The core language giving all the building blocks including variables, data types and
literals etc.
The C++ Standard Library giving a rich set of functions manipulating files, strings etc.
The Standard Template Library (STL) giving a rich set of methods manipulating data
structures etc.

The ANSI Standard


The ANSI standard is an attempt to ensure that C++ is portable -- that code you write for
Microsoft's compiler will compile without errors, using a compiler on a Mac, Unix, a Windows
box, or an Alpha.
The ANSI standard has been stable for a while, and all the major C++ compiler manufacturers
support the ANSI standard.
The Standard Function Library:
The standard function library is divided into the following categories:

I/O
String and character handling
Mathematical
Time, date, and localization
Dynamic allocation
Miscellaneous
Wide-character functions

The Object Oriented Class Library:


Standard C++ Object Oriented Library defines an extensive set of classes that provide support
for a number of common activities, including I/O, strings, and numeric processing. This library
includes following:

The Standard C++ I/O Classes

The String Class

The Numeric Classes

The STL Container Classes

The STL Algorithms

The STL Function Objects

The STL Iterators

The STL Allocators

The Localization library

Exception Handling Classes

Miscellaneous Support Library

Input/Output with files


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.
Introduction to various C++ compilers
C++ is a huge language so much that it uses various sets of instructions from different parts to do
its work. Some of these instructions come in computer files that you simply "put" in your
program. These instructions or files are also called libraries.
#include iostream.h
There are usually two kinds of libraries or files you will use in our programs: libraries that
came with C++, and those that we write. To include our own library, we would enclose it
between double quotes, like this

#include "books.h"
When we include a library that came with C++, we enclose it between < and > as follows:
#include <iostream.h>
Following this same technique, we can add as many libraries as we can. Before adding a file,
we will need to know what that file is and why we need it. This will mostly depend on our
application. For example, we can include a library called stdio like this:
#include <iostream.h>
#include <stdio.h>
Testing the C++ program in Turbo C++/Borland C++/ MicroSoft VC++/GNU C++
compiler.
Borland C++BuilderX
Borland C++BuilderX is a commercial programming environment developed by Borland. To help
programmers, Borland published a free version, called Personal Edition, that we can download and
use.
1. On the main menu of C++BuilderX, click File -> New...
2.

In the Object Gallery dialog box, click New Console

3. Click OK
4. In the New Console Application - Step 1 of 3, enter the name of the new application
in the Name edit box. In this case, we can type Exercise1

5. Click Next

6. In the New Console Application Wizard - Step 2 of 3, accept all defaults and click
Next
7. In the New Console Application Wizard - Step 3 of 3, click the check box under
Create
8. Click Untitled1 and delete it to replace it with Exercise

9. Click Finish
10. In the Project Content frame, double-click Exercise.cpp to display it in the right
frame

11. To execute the application, on the main menu, click Run -> Run Project

UNIT II Classes and Objects


All C++ programs are composed of following two fundamental elements:

Program statements (code): This is the part of a program that performs actions and they
are called functions.

Program data: The data is the information of the program which affected by the program
functions.

Encapsulation is an Object Oriented Programming concept that binds together the data and
functions that manipulate the data, and that keeps both safe from outside interference and misuse.
Data encapsulation led to the important OOP concept of data hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use them and data
abstraction is a mechanism of exposing only the interfaces and hiding the implementation details
from the user.
C++ supports the properties of encapsulation and data hiding through the creation of userdefined types, called classes
Information hiding:Data abstraction refers to, providing only essential information to the outside word and hiding
their background details ie. to represent the needed information in program without presenting
the details.
Data abstraction is a programming (and design) technique that relies on the separation of
interface and implementation. C++ classes provides great level of data abstraction. They provide
sufficient public methods to the outside world to play with the functionality of the object and to
manipulate object data ie. state without actually knowing how class has been implemented
internally.
For example, our program can make a call to the sort() function without knowing what algorithm
the function actually uses to sort the given values. In fact, the underlying implementation of the
sorting functionality could change between releases of the library, and as long as the interface
stays the same, your function call will still work.

Benefits of Data Abstraction:


Data abstraction provide two important advantages:

Class internals are protected from inadvertent user-level errors, which might corrupt the
state of the object.

The class implementation may evolve over time in response to changing requirements or
bug reports without requiring change in user-level code.

By defining data members only in the private section of the class, the class author is free to make
changes in the data. If the implementation changes, only the class code needs to be examined to
see what affect the change may have. If data are public, then any function that directly accesses
the data members of the old representation might be broken.
Abstract data Type:An abstract data type is simply an encapsulation that includes only the data representation of
one specific data type and the subprograms that provide the operations for that type. It is a
data type that satisfies two conditions:1) The representation, or definition, of the type and the operations are contained in a single
syntactic unit.
2) The representation of objects of the type is hidden from the program units that use the
type, so only direct operations possible on those objects are those provided in the types
definition

C++ Class :
When we define a class, we define a blueprint for a data type. This doesn't actually define any
data, but it does define what the class name means, that is, what an object of the class will consist
of and what operations can be performed on such an object.
A class definition starts with the keyword class followed by the class name; and the class body,
enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a
list of declarations. For example we defined the Box data type using the keyword class as
follows:
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that follow it. A
public member can be accessed from outside the class anywhere within the scope of the class
object.

C++ Objects:
A class provides the blueprints for objects, so basically an object is created from a class. We
declare objects of a class with exactly the same sort of declaration that we declare variables of
basic types. Following statements declare two objects of class Box:
Box Box1;

// Declare Box1 of type Box

Box Box2;

// Declare Box2 of type Box

Both of the objects Box1 and Box2 will have their own copy of data members.
Member /function In C++:A function is a group of statements that together perform a task. Every C++ program has at least
one function which is main(), and all the most trivial programs can define additional functions
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the
parts of a function:

Return Type: A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.

Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.

Parameters: A parameter is like a placeholder. When a function is invoked, we pass a


value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.

Function Body: The function body contains a collection of statements that define what
the function does
Defining attributes in C++ Programming:-

The first part of the class is the private part, where the attributes of the class are listed.
The attributes of a class are defined in a very similar way to the way in which variables
are defined. The only difference is that they cannot be given an initial value. The format
of the declaration is :
<type> <identifier>;
For example:
string name;
int age;
C++ class declaration, (references, this pointer):A class is an expanded concept of a data structure: instead of holding only data, it can hold both
data and functions.
An object is an instantiation of a class. In terms of variables, a class would be the type, and an
object would be the variable.
Classes are generally declared using the keyword class, with the following format:
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
Where class_name is a valid identifier for the class, object_names is an optional list of
names for objects of this class. The body of the declaration can contain members, that can
be either data or function declarations, and optionally access specifiers.

Function overloading in C++:


C++ allows us to specify more than one definition for a function name or an operator in the same
scope, which is called function overloading and operator overloading respectively.
An overloaded declaration is a declaration that had been declared with the same name as a
previously declared declaration in the same scope, except that both declarations have different
arguments and obviously different definition (implementation).
When we call an overloaded function or operator, the compiler determines the most appropriate
definition to use by comparing the argument types you used to call the function or operator with
the parameter types specified in the definitions. The process of selecting the most appropriate

overloaded function or operator is called overload resolution. We can have multiple definitions
for the same function name in the same scope. The definition of the function must differ from
each other by the types and/or the number of arguments in the argument list. We cannot overload
function declarations that differ only by return type

Constructor
A class constructor is a special member function of a class that is executed whenever we create
new objects of that class.
A constructor will have exact same name as the class and it does not have any return type at all,
not even void. Constructors can be very useful for setting initial values for certain member
variables

The Class Destructor:


A destructor is a special member function of a class that is executed whenever an object of it's
class goes out of scope or whenever the delete expression is applied to a pointer to the object of
that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither
return a value nor can it take any parameters. Destructor can be very useful for releasing
resources before coming out of the program like closing files, releasing memories etc.
Instantiation of objects :Instantiation of a class literally means creating an instance of a class. This is the process of
allocating memory for an object that we can use in your program.
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;

Default parameter value :A default parameter is a function parameter that has a default value provided to it. If the user
does not supply a value for this parameter, the default value will be used. If the user does supply
a value for the default parameter, the user-supplied value is used.

void PrintValues(int nValue1, int nValue2=10)


{
using namespace std;
cout << "1st value: " << nValue1 << endl;
cout << "2nd value: " << nValue2 << endl;
}
int main()
{
PrintValues(1); // nValue2 will use default parameter of 10
PrintValues(3, 4); // override default value for nValue2
}
This program produces the following output:
1st value: 1
2nd value: 10
1st value: 3
2nd value: 4
In the first function call, the caller did not supply an argument for nValue2, so the function used
the default value of 10. In the second call, the caller did supply a value for nValue2, so the userSupplied value was used.
Default parameters are an excellent option when the function needs a value that the user may or
may not want to override. For example, here are a few function prototypes for which default
parameters might be commonly used:

Dynamic Memory Allocation


Until now, in all our programs, we have only had as much memory available as we declared for
our variables, having the size of all of them to be determined in the source code, before the
execution of the program. But, what if we need a variable amount of memory that can only be
determined during runtime. For example, in the case that we need some user input to determine
the necessary amount of memory space. For that we need dynamic memory, for which C++
integrates the operators new and delete.

Operators new and new[]


In order to request dynamic memory we use the operator new. New is followed by a data type
specifier and -if a sequence of more than one element is required- the number of these within
brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its form

is:
pointer = new type
pointer = new type [number_of_elements]

Operators delete and delete[]


Since the necessity of dynamic memory is usually limited to specific moments within a program,
once it is no longer needed it should be freed so that the memory becomes available again for
other requests of dynamic memory.

Garbage Collection is a process that many Operating Systems and some applications,
especially services perform. The purpose of Garbage Collection is to recover or reorganise
system resources such as available blocks of RAM to prevent failure due to resource starvation.
Many applications allocate blocks of RAM for storing variables. When the blocks of RAM are
no longer required they are returned to the application. The addresses of the blocks are usually
stored on a free list and when the application later requests more RAM, it checks the free list
first. The effect of this over a period of time is to split RAM into smaller and smaller blocks.
Eventually an application will request a block that is too big and fail. Garbage Collection merges
all the free blocks into one large block. In older languages like C++ programmers had to write
their own Garbage Collection routines but newer languages like C# provide this.

Abstract class:An interface describes the behavior or capabilities of a C++ class without committing to a
particular implementation of that class. The C++ interfaces are implemented using abstract
classes and these abstract classes should not be confused with data abstraction which is a concept
of keeping implementation detail separate from associated data. The purpose of an abstract class
(often referred to as an ABC) is to provide an appropriate base class from which other classes
can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface.
Attempting to instantiate an object of an abstract class causes a compilation error.

Metaclass: A class whose instances are classes.

UNIT III
Inheritance and Polymorphism:
One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance allows us to define a class in terms of another class, which makes it easier to create
and maintain an application. This also provides an opportunity to reuse the code functionality
and fast implementation time.
When creating a class, instead of writing completely new data members and member functions,
the programmer can designate that the new class should inherit the members of an existing class.
This existing class is called the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal,
dog IS-A mammal hence dog IS-A animal as well and so on.

Type of Inheritance ( class hierarchy)


When deriving a class from a base class, the base class may be inherited through public,
protected or private inheritance. The type of inheritance is specified by the access-specifier as
explained above.
DERIVATION
We hardly use protected or private inheritance but public inheritance is commonly used. While
using different type of inheritance, following rules are applied:

Public Inheritance: When deriving a class from a public base class, public members of
the base class become public members of the derived class and protected members of the
base class become protected members of the derived class. A base class's private
members are never accessible directly from a derived class, but can be accessed through
calls to the public and protected members of the base class.

Protected Inheritance: When deriving from a protected base class, public and protected
members of the base class become protected members of the derived class.

Private Inheritance: When deriving from a private base class, public and protected
members of the base class become private members of the derived class.

Compositions:

Typically use normal member variables


Can use pointer values if the composition class automatically handles
allocation/deallocation

Responsible for creation/destruction of subclasses

Aggregations:

Typically use pointer variables that point to an object that lives outside the scope of the
aggregate class
Can use reference values that point to an object that lives outside the scope of the
aggregate class
Not responsible for creating/destroying subclasses

Polymorphism (Categorization of polymorphism techniques)


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.





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
Virtual Function:
If there are member function with same name in derived classes, virtual functions gives
programmer capability to call member function of different class by a same function call
depending upon different context. This feature in C++ programming is known as polymorphism
which is one of the important feature of OOP.
If a base class and derived class has same function and if you write code to access that function
using pointer of base class then, the function in the base class is executed even if, the object of
derived class is referenced with that pointer variable.

Pure Virtual Functions:


It's possible that we want to include a virtual function in a base class so that it may be redefined
in a derived class to suit the objects of that class, but that there is no meaningful definition we
could give for the function in the base class.
We can change the virtual function area() in the base class to the following:
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.
Run-time:
The run-time polymorphism is implemented with inheritance and virtual functions.
Compile-time:
The compile-time polymorphism is implemented with templates.
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.
Polymorphism by parameter
Parametric polymorphism is obtained when a function works uniformly on a range of types;
these types normally exhibit some common structure. Ad-hoc polymorphism is obtained when a
function works, or appears to work, on several different types (which may not exhibit a common
structure) and may behave in unrelated ways for each type."
Operator Overloading
The meaning of operators are fixed for basic types like: int, float, double etc in C++ language.
For example: If you want to add two integers then, + operator is used. But, for user-defined
types(like: objects),we can define the meaning of operator, i.e, we can redefine the way that
operator works. For example: If there are two objects of a class that contain string as its data
member, then we can use + operator to concatenate two strings. Suppose, instead of strings if
that class contains integer data member, then we can use + operator to add integers. This feature
in C++ programming that allows programmer to redefine the meaning of operator when they
operate on class objects is known as operator overloading.
Early binding:
When a non virtual class member function is called, compiler places the code to call the function
by symbol name. Thus the function call jumps to a location that is decided by compile time or
link time.
class base
{
void funct1(void);
};
base b;
b.funct1(); //compiler call address of base::function() symbol
Late binding: When virtual function call is made through a base-class pointer, the compiler
quietly inserts code to fetch the VPTR and look up the function address in the VTABLE, thus
calling the right function and this is called late/dynamic binding.
class base
{
virtual void funct1(void) = 0;
};
class derived: public base
{
void funct1(void){}

};
class derived2: public base
{
void funct1(void){}
};
derived d;
base * b = d;
//See how b calls function funct1() of d in three steps
//1) get d::vtable address from b::vptr
// [value: b::vptr points to d::vtable]
//2) get b::funct1() address from b::vtable entry 0
// [value: function address= d::vtable[0]]
//3) call pointer entry 0 of vtable 0
// [ call address pointed by d::vtable[0] ]
b->funct1();
derived2 d2;
base * b = d2;
//See how b calls function funct1() of d2 in three steps
//1) get d2::vtable address from b::vptr
// [value: b::vptr points to d::vtable]
//2) get b::funct1() address from b::vtable entry 0
// [value: function address= d::vtable[0]]
//3) call pointer entry 0 of vtable 0
// [ call address pointed by d::vtable[0] ]
b->funct1();
An overloaded operator is called an operator function. We can declare an operator function
with the keyword operator preceding the operator. Overloaded operators are distinct from
overloaded functions, but like overloaded functions, they are distinguished by the number and
types of operands used with the operator.
Consider the standard + (plus) operator. When this operator is used with operands of different
standard types, the operators have slightly different meanings. For example, the addition of two
integers is not implemented in the same way as the addition of two floating-point numbers

// This example illustrates overloading the plus (+) operator.


#include <iostream>
using namespace std;
class complx
{
double real,
imag;
public:
complx( double real = 0., double imag = 0.); // constructor
complx operator+(const complx&) const;
// operator+()
};
// define constructor
complx::complx( double r, double i )
{
real = r; imag = i;
}
// define overloaded + (plus) operator
complx complx::operator+ (const complx& c) const
{
complx result;
result.real = (this->real + c.real);
result.imag = (this->imag + c.imag);
return result;
}
int main()
{
complx x(4,4);
complx y(6,6);
complx z = x + y; // calls complx::operator+()
}

UNIT-IV
Generic Programming Introduction
In the simplest definition, generic programming is a style of computer programming in which
algorithms are written in terms of to-be-specified-later types that are then instantiated when
needed for specific types provided as parameters
C++ provides unique abilities to express the ideas of Generic Programming through templates.
Templates provide a form of parametric polymorphism that allows the expression of generic
algorithms and data structures. The instantiation mechanism of C++ templates insures that when
a generic algorithm or data structure is used, a fully-optimized and specialized version will be
created and tailored for that particular use, allowing generic algorithms to be as efficient as their
non-generic counterparts.

Templates
Templates are the foundation of generic programming which involves writing code in a way that
is independent of any particular type. A template is a blueprint or formula for creating a generic
class or a function. The library containers like iterators, and algorithms are examples of generic
programming and have been developed using template concept. There is a single definition of
each container, such as vector, but we can define many different kinds of vectors for example,
vector <int> or vector <string>.

Template functions
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;
EXAMPLE

// function template
#include <iostream>
using namespace std;
template <class T>
T GetMax (T a, T b) {
T result;
result = (a>b)? a : b;
return (result);
}
int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax<int>(i,j);
n=GetMax<long>(l,m);
cout << k << endl;
cout << n << endl;
return 0;
}
In this case, we have used T as the template parameter name instead of myType because it is shorter
and in fact is a very common template parameter name. In the example above we used the function
template GetMax() twice. The first time with arguments of type int and the second one with
arguments of type long. The compiler has instantiated and then called each time the appropriate
version of the function.

Overloading of template functions


You may overload a function template either by a non-template function or by another function
template. If you call the name of an overloaded function template, the compiler will try to deduce
its template arguments and check its explicitly declared template arguments. If successful, it will
instantiate a function template specialization, then add this specialization to the set of candidate
functions used in overload resolution. The compiler proceeds with overload resolution, choosing
the most appropriate function from the set of candidate functions. Non-template functions take
precedence over template functions. The following example describes this:
#include <iostream>
using namespace std;
template<class T> void f(T x, T y) { cout << "Template" << endl; }
void f(int w, int z) { cout << "Non-template" << endl; }
int main() {
f( 1 , 2 );
f('a', 'b');
f( 1 , 'b');
}
Output:

Non-template
Template
Non-template

Overriding inheritance methods


When a method in a derived class has the same name, arguments in numbers and types and the
same return type the method says to override that base class method. The base class has an
overloaded method with the same name as the overridden method, that method says to be hided
and cannot be accessed by the derived class without the special class (baseclass::) notation.

Files and Exception Handling: Persistant objects


A persistent object can live after the program which created it has stopped. Persistent objects can
even outlive different versions of the creating program, can outlive the disk system, the operating
system, or even the hardware on which the OS was running when they were created. The
challenge with persistent objects is to effectively store their member function code out on
secondary storage along with their data bits. This is non-trivial when you have to do it yourself.
In C++, you have to do it yourself. C++ databases can help hide the mechanism for all this.
Streams and files
The C++ standard libraries provide an extensive set of input/output capabilities . C++ I/O occurs
in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk
drive, or a network connection etc. to main memory, this is called input operation and if bytes
flow from main memory to a device like a display screen, a printer, a disk drive, or a network
connection, etc, this is called output operation.
Of course, it's also possible to open files or other I/O sources)explicitly. We can open files using
the function fopen; certain systems may also provide specialized ways of opening streams
connected to I/O devices or set up in more exotic ways. A successful call to fopen returns a
pointer of type FILE *, that is, ``pointer to FILE,'' where FILE is a special type defined by
<stdio.h>. A FILE * (also called ``file pointer'') is the handle by which we refer to an I/O
stream in C++.

I/O Library Header Files:


There are

following header files important to C++ programs:

Header File

Function and Description

<iostream>

This file defines the cin, cout, cerr and clog objects, which correspond to the

standard input stream, the standard output stream, the un-buffered standard
error stream and the buffered standard error stream, respectively.
<iomanip>

This file declares services useful for performing formatted I/O with so-called
parameterized stream manipulators, such as setw and setprecision.

<fstream>

This file declares services for user-controlled file processing. We will discuss
about it in detail in File and Stream related chapter.

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 << .
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 >>
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

Namespaces
Namespaces allow to group entities like classes, objects and functions under a name. This way
the global scope can be divided in "sub-scopes", each one with its own name.
The format of namespaces is:
namespace identifier
{
entities
}
Where identifier is any valid identifier and entities is the set of classes, objects and functions that
are included within the namespace. The functionality of namespaces is especially useful in the
case that there is a possibility that a global object or function uses the same identifier as another
one, causing redefinition errors.
Example
using namespace example

#include <iostream>
using namespace std;
namespace first
{
int x = 5;
}
namespace second
{
double x = 3.1416;
}
int main () {
{
using namespace first;
cout << x << endl;
}
{
using namespace second;
cout << x << endl;
}
return 0;

}
OUTPUT
5
3.1416

C++ predefined streams


C++ provides the following predefined streams:
cin The standard input stream
cout The standard output stream
cerr The standard error stream, unit-buffered such that characters sent to this stream are flushed
on each output operation
clog The buffered error stream
All predefined streams are tied to cout. When you use cin, cerr, or clog, cout gets flushed
sending the contents of cout to the ultimate consumer.
C++ standard streams create all I/O to I/O streams:
Input to cin comes from stdin (unless cin is redirected)
cout output goes to stdout (unless cout is redirected)
cerr output goes to stderr (unit-buffered) (unless cerr is redirected)
clog output goes to stderr (unless clog is redirected)

Error handling during file operations


we perform the file operation without any knowledge of failure or success of the function
open( ) that opens the file. There are many reasons and they may result in error during
read/write operation of the program.
(1) An attempt to read a file which does not exist.
(2) The file name specified for opening a new file may already exist.
(3) An attempt to read contents of file when file pointer is at the end of file.
(4) Insufficient disk space.
(5) Invalid file name specified by the programmer.
(6) An effort to write data to the file that is opened in read only mode.
(7) A file opened may already be opened by another program.
(8) An attempt to open read only file for writing operation.
(9) Device error.
ERROR HANDLING FUNCTIONS
FUNCTION
eof()
fail()
bad()
good()

RETURN VALUE & MEANING


Return true if end-of-file is encountered while reading
Return true when an input or output operation has failed .
Return true if an invalid operation is attempted or any unrecoverable error has
occured
Return true if no error has occured

These functions may be used in appropriate places in a program to locate the status of a file
stream and therefore to take the necessary corrective measures.

Command Line Arguments


In C++ it is possible to accept command line arguments. Command-line arguments are given
after the name of a program in command-line operating systems like DOS or Linux, and are
passed in to the program from the operating system. To use command line arguments in your
program, you must first understand the full declaration of the main function, which previously
has accepted no arguments. In fact, main can actually accept two arguments: one argument is
number of command line arguments, and the other argument is a full list of all of the command
line arguments.

Types of Exception
An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.There are many different derived exception types .Here, we look at
various exception types

ArgumentException
ArgumentNullException
ArgumentOutOfRangeException
ArrayTypeMismatchException
DirectoryNotFoundException
DivideByZeroException
FileNotFoundException
FormatException
IndexOutOfRangeException
InvalidCastException
InvalidOperationException
IOException
KeyNotFoundException
NullReferenceException
OutOfMemoryException
OverflowException
StackOverflowException
TypeInitializationException

Catching and Handling Exceptions


Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.

throw: A program throws an exception when a problem shows up. This is done using a
throw keyword.

catch: A program catches an exception with an exception handler at the place in a


program where you want to handle the problem. The catch keyword indicates the
catching of an exception.

try: A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.

Assuming a block will raise and exception, a method catches an exception using a combination
of the try and catch keywords. A try/catch block is placed around the code that might generate
an exception. Code within a try/catch block is referred to as protected code, and the syntax for
using try/catch looks like the following:
try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block

}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in case your
try block raises more than one exceptions in different situations.

Throwing Exceptions:
Exceptions can be thrown anywhere within a code block using throw statements. The operand of
the throw statements determines a type for the exception and can be any expression and the type
of the result of the expression determines the type of exception thrown.
Following is an example of throwing an exception when dividing by zero condition occurs:
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}

Catching Exceptions:
The catch block following the try block catches any exception. You can specify what type of
exception you want to catch and this is determined by the exception declaration that appears in
parentheses following the keyword catch.
try
{
// protected code
}catch( ExceptionName e )
{
// code to handle ExceptionName exception
}

Above code will catch an exception of ExceptionName type. If you want to specify that a catch
block should handle any type of exception that is thrown in a try block, you must put an ellipsis,
..., between the parentheses enclosing the exception declaration as follows:
try
{
// protected code
}catch(...)
{
// code to handle any exception
}
The following is an example which throws a division by zero exception and we catch it in catch
block.
#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Because we are raising an exception of type const char*, so while catching this exception, we
have to use const char* in catch block. If we compile and run above code, this would produce
following result:

Division by zero condition!

TEXT BOOKS
[T1] Ashok N. Kamthane, Object-Oriented Programming With Ansi And Turbo C++, Pearson
Education.
[T2] A.R.Venugopal, Rajkumar, T. Ravishanker Mastering C++, TMH, 1997.
[T3] E. Balguruswamy, C++ , TMH Publication ISBN 0-07-462038-x .
REFERENCE BOOKS
[R1] Mahesh Bhave, Object Oriented Programming with C++, Pearson Education.
[R2] D . Parasons, Object Oriented Programming with C++, BPB Publication.
[R3]Steven C. Lawlor, The Art of Programming Computer Science with C++, Vikas
Publication.
[R4] Schildt Herbert, C++: The Complete Reference, 4th Ed., Tata McGraw Hill, 1999.
[R5] R. Lafore, Object Oriented Programming using C++, Galgotia Publications, 2004.

You might also like