Sunteți pe pagina 1din 83

CS6456 OBJECT ORIENTED PROGRAMMING

INHERITANCE
>>>INTRODUCTION
A derived class extends its features by inheriting the properties of another class
(base class) and adding features of its own.
The derivation of a derived class specifies its relationship with the base class, in
addition to its own features.
Syntax
Class derivedclass_name:[visibility mode] baseclass_name
{
/*Members of the derived class, They can also access the members of the base class*/
}

The : denotes that the class is derived from another class


The visibility mode specifies the inheritance type: public,private or protected.
The visibility mode is optional. The default visibility mode is private.

>>PUBLIC, PRIVATE AND PROTECTED DERIVATIONS(or) VISIBILITY MODES

When a class is derived from some other class, the data members of that class
are made available to the derived class. But, which data member is available

depends on the type of derivation used for inheritance.


There are three types of inheritance.
Public Derivation
Private Derivation
Protected Derivation

>>PUBLIC DERIVATION
The base class is derived with public visibility mode. The syntax of the public
derivation is as follows.
Syntax
Class base // Base class
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 1

CS6456 OBJECT ORIENTED PROGRAMMING


---------------};
Class derived: public base // Derived class
{
-------------------};
THE FOLLOWING CHANGES ARE MADE DURING THE PUBLIC DERIVATION OF DERIVED
CLASS

Public
members of
the base class

Protected
members of the
base class
Becom
es

Becom
es

Public
members of

Protected
members of the
Derived class

SINGLE INHERITANCE WITH PUBLIC DERIVATION


#include<iostream.h>
#include<conio.h>
class A

Private
members of the
base class

// Base class

{
private:
int a;
public:
int b;
Prepared by A.V. KALPANA, Asst. ProfessorPage 2

Cannot be
derived

CS6456 OBJECT ORIENTED PROGRAMMING


void setA(int value)
{
a = value;
}
};
class B : public A

// End of the base class definition


// Derived class

{
private:
int x;
public:
int y;
void setB()
{
x=value;
}
void main()
{
clrscr();
B obj;
obj.a=10; //Error
obj.x=10;//Error
obj.b=10;
obj.y=10;
obj.setA(20);
obj.setB(30);
getch(); }
SINGLE INHERITANCE WITH PRIVATE DERIVATION
Prepared by A.V. KALPANA, Asst. ProfessorPage 3

CS6456 OBJECT ORIENTED PROGRAMMING


PRIVATE DERIVATION
The base class is derived with Private visibility mode. The syntax of the public
derivation is as follows.
Syntax
Class base // Base class
{
-----------};
Class derived: private base // Derived class
{
----------};
THE FOLLOWING CHANGES ARE MADE DURING THE PUBLIC DERIVATION OF DERIVED
CLASS

Public
members of
the base class

Protected
members of the
base class

Private
members of the
base class

Becom

Cannot be
Privatemember
es
derived
s of the Derived
class the visibility mode in the derived class is changed to
For the same program,
private. In this case, the public and protected members of the base class become
the private members of the derived class, so the inherited members(base class)
Prepared by A.V. KALPANA, Asst. ProfessorPage 4

CS6456 OBJECT ORIENTED PROGRAMMING


can be used only inside the derived class & cannot be accessed in main(). The
privately derived class is not available for further inheritance.
EXAMPLE
#include<iostream.h>
#include<conio.h>
class A

// Base class

{
protected:
int a;
public:
int b;
void setA(int value)
{
a = value;
}
};

class B : public A

// End of the base class definition

// Derived class

{
private:
int x;
public:
int y;
void setB()
{
x=value;

Prepared by A.V. KALPANA, Asst. ProfessorPage 5

CS6456 OBJECT ORIENTED PROGRAMMING


}
void main()
{
clrscr();
B obj;
obj.a=10; //Error
obj.x=10;//Error
obj.b=10;//Error
obj.y=10;
obj.setA(20);//Error
obj.setB(30);
getch();
}
>>PROTECTED DERIVATION
The base class is derived with Protectedvisibility mode. The syntax of the public
derivation is as follows.
Syntax
Class base // Base class
{
};
Class derived: protected base // Derived class
{
};

Prepared by A.V. KALPANA, Asst. ProfessorPage 6

CS6456 OBJECT ORIENTED PROGRAMMING


THE FOLLOWING CHANGES ARE MADE DURING THE PUBLIC DERIVATION OF DERIVED
CLASS

Public
members of
the base class

Protected
members of the
base class

Private
members of the
base class

Becom
es

Cannot be
Protectedmemb
derived
ers of the
For the same
program,class
the visibility mode in the derived class is changed to
Derived
protected. In this case, the public and protected members of the base class
become the protected members of the derived class, so the inherited
members(base class) can be used only inside the derived class & cannot be
accessed in main(). The protectedly derived class is can be further inherited.
EXAMPLE
#include<iostream.h>
#include<conio.h>
class A

// Base class

{
private:
int a;
public:
int b;
void setA(int value)
{
a = value;
}
Prepared by A.V. KALPANA, Asst. ProfessorPage 7

CS6456 OBJECT ORIENTED PROGRAMMING


};

// End of the base class definition

class B : public A

// Derived class

{
private:
int x;
public:
int y;
void setB()
{
x=value;
}
void main()
{
clrscr();
B obj;
obj.a=10; //Error
obj.x=10;//Error
obj.b=10;//Error
obj.y=10;//Error
obj.setA(20);//Error
obj.setB(30);
getch();
}
Note: The only difference between the private and protected derivation is that,

With private derivation, the inherited base class members are private to the
base class and cannot be further inherited.
With protected derivation, the inherited base class members are protected to
the
and isAsst.
available
for further8inheritance
Prepared
bybase
A.V. class
KALPANA,
ProfessorPage

CS6456 OBJECT ORIENTED PROGRAMMING

Inheritance is the process by which objects of one class acquire the properties of
the objects of another class. This supports the concept of hierarchical
classification.
Inheritance is the object-oriented feature that supports reusability.

Base class

Derived class

Base class:
It is the class whose members(variables + functions) are inherited by another class.
Derived class:
It is the class that inherits the members(variables + functions) from the base class.
It contains the inherited members as well as its own members.
ADVANTAGES:
1. The concept of inheritance allows the code to be reused as many times as
needed.
2. Saves the time and effort in program development.

TYPES OF INHERITANCE

Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Multipath Inheritance or Virtual base class or Diamond Inheritance

>>SINGLE INHERITANCE
Deriving a class from only one base class is called as single inheritance.
Prepared by A.V. KALPANA, Asst. ProfessorPage 9

CS6456 OBJECT ORIENTED PROGRAMMING


Base class
Derived class
B
class Base class name
{
..
};
class Derived class-name: visibility mode base class-name
{
..
..
};

Example:
#include<iostream.h>
#include<conio.h>
class Person

//Base class

{
char *name;
char sex;
int age;
public:
void read()
{
cout<<Name:;
cin>>name;
cout<<Sex:;
cin>>sex;
Prepared by A.V. KALPANA, Asst. ProfessorPage 10

Syntax:

CS6456 OBJECT ORIENTED PROGRAMMING


cout<<Age:;
cin>>age;
}
void display()
{
cout<<Name:<<name<<endl;
cout<<Sex:<<sex<<endl;
cout<<Age:<<age<<endl;
}
};
class Student : public Person

//derived class

{
private:
int rollno;
char *branch;
public:
void read()
{
Person::read();
cout<<Roll No:;
cin>>rollno;
cout<<Branch:;
cin>>branch;
}
void display()
{
Person::display();
Prepared by A.V. KALPANA, Asst. ProfessorPage 11

CS6456 OBJECT ORIENTED PROGRAMMING


cout<<Roll No:<<rollno<<endl;
cout<<Branch:<<branch<<endl;
}
};
void main()
{
clrscr();
Student s;
s.read();
s.display();
getch();
}

>>MULTIPLE INHERITANCE

Deriving a class from two or more base classes is called as multiple inheritance.

Base classes

Derived class

Multiple inheritance contains more than one derived class and a single base class.

Syntax:

Prepared by A.V. KALPANA, Asst. ProfessorPage 12

CS6456 OBJECT ORIENTED PROGRAMMING


class baseclass1
{
.
};
class baseclass2
{

};
class Derived: public baseclass1, public baseclass2
{

};
Example:
#include<iostream.h>
#include<conio.h>
class InternalExam

//Base class 1

{
protected:
int sub1, sub2;
public:
void read()
{
cout<<Enter the internal marks scored in Subject1:<<
cin>>sub2
cout<<Enter the internal marks scored in Subject2:<<
cin>>sub2;
}
void display()
{
cout<<Internal marks scored in Subject1:<<sub1<<endl;
Prepared by A.V. KALPANA, Asst. ProfessorPage 13

CS6456 OBJECT ORIENTED PROGRAMMING


cout<<Internal marks scored in Subject2:<<sub12<<endl;
};
class ExternalExam

//Base class 1

{
protected:
int sub1, sub2;
public:
void read()
{
cout<<Enter the external marks scored in Subject1:<<
cin>>sub1;
cout<<Enter the external marks scored in Subject2:<<
cin>>sub2;
}
void display()
{
cout<<External marks scored in Subject1:<<sub1<<endl;
cout<<External marks scored in Subject2:<<sub12<<endl;
};
class Result: public InternalExam, public External Exam
{
private:
int sub1total, sub2total;
public:
void read()
{
InternalExam::read();
Prepared by A.V. KALPANA, Asst. ProfessorPage 14

CS6456 OBJECT ORIENTED PROGRAMMING


ExternalExam::read();
}
void total()
{
sub1total = InternalExam::sub1+ExternalExam::sub1;
sub2total = InternalExam::sub2+InternalExam::sub2;
}
void display()

OUTPUT:

Enter the internal marks scored in Subject1: 18

InternalExam::display();

Enter the internal marks scored in Subject2: 20

ExternalExam::display();

Enter the external marks scored in Subject1: 75

cout<<Subject1 Marks:<<sub1total; Enter the external marks scored in Subject2: 77


Internal marks scored in Subject1: 18
cout<<Subject2 Marks:<<sub2total;
Internal marks scored in Subject2: 20
}
External marks scored in Subject1: 75
};
External marks scored in Subject2: 77
void main()
Subject1 Marks: 93

Subject2 Marks: 97

clrscr();
Result r;
r.read();
r.total();
r.display();
getch();
}

Prepared by A.V. KALPANA, Asst. ProfessorPage 15

CS6456 OBJECT ORIENTED PROGRAMMING


>>MULTILEVEL INHERITANCE
Derivation of a class from another derived class is called as multi-level
inheritance.
Base class

Intermediate Derived class

Derived class

Deriving a class from another derived class is stated as multilevel inheritance. The
following program illustrates the multilevel inheritance
Syntax:
class Baseclass
{.};
class Derived-classname1: public Baseclass
{..};
class Derived-classname2: public Derived-classname1
{
.
};
EXAMPLE
#include <iostream.h>
#include<conio.h>
class Person

//Base class

{
char *name;
char sex;
int age;
public:
Prepared by A.V. KALPANA, Asst. ProfessorPage 16

CS6456 OBJECT ORIENTED PROGRAMMING


void read()
{
cout<<Name:;
cin>>name;
cout<<Sex:;

Name:RAJ

cin>>sex;

Sex:M

cout<<Age:;
cin>>age;
}
void display()
{
cout<<Name:<<name<<endl;
cout<<Sex:<<sex<<endl;

Age:20
Roll No:1234
Branch:CSE
Enter the marks scored in Subject1:85
Enter the marks scored in Subject2:90
Name:RAJ

cout<<Age:<<age<<endl;

Sex:M

Age:20

};

Roll No:1234

class Student : public Person

//Intermediate
derived class
Branch:CSE

Subject1 Marks:85

private:

Subject2 Marks:90

int rollno;

Total Marks:175

char *branch;
public:
void read()
{
Person::read();
cout<<Roll No:;
cin>>rollno;
Prepared by A.V. KALPANA, Asst. ProfessorPage 17

CS6456 OBJECT ORIENTED PROGRAMMING


cout<<Branch:;
cin>>branch;
}
void display()
{
Person::display();
cout<<Roll No:<<rollno<<endl;
cout<<Branch:<<branch<<endl;
}
};
class Exam: public Student
{
private:
int sub1, sub2;
public:
void read()
{
Student::read();
cout<<Enter the marks scored in Subject1:;
cin>>sub1;
cout<<Enter the marks scored in Subject2:;
cin>>sub2;
}
void display()
{
Student::display();
cout<<Subject1 Marks:<<sub1<<endl;
Prepared by A.V. KALPANA, Asst. ProfessorPage 18

CS6456 OBJECT ORIENTED PROGRAMMING


cout<<Subject2 Marks:<<sub2<<endl;
cout<<Total Marks:<<sub1+sub2<<endl;
}
};
void main()
{
clrscr();
Exam e;
e.read();
e.display();
getch();
}

>>HYBRID INHERITANCE
Derivation of a class involving more than one form of inheritance is called as
hybrid inheritance.

A
B

D
This is the combination of three types of inheritance: hierarchical, multiple and
multi-level inheritance. Combination of more than one form of inheritance is
called as the hybrid inheritance.

Prepared by A.V. KALPANA, Asst. ProfessorPage 19

CS6456 OBJECT ORIENTED PROGRAMMING


Syntax:
class Base-class-name1
{
.
};
class Derived-class-name1: visibility-mode Base-class-name1
{
..
};
class Base-class-name2
{

};
class Derived-class-name2: visibility-mode Derived class-name1, visibility-mode
Base-class-name2
{

};
EXAMPLE
The given program is the combination of multilevel and multiple inheritance
#include <iostream.h>
#include<conio.h>
class Person

//Base class

{
char *name;
char sex;
int age;
public:
void read()
{
cout<<Name:;
cin>>name;
Prepared by A.V. KALPANA, Asst. ProfessorPage 20

CS6456 OBJECT ORIENTED PROGRAMMING


cout<<Sex:;
cin>>sex;
cout<<Age:;
cin>>age;
}

OUTPUT:
Name: RAM

void display()

Sex: M

Age: 20

cout<<Name:<<name<<endl;
cout<<Sex:<<sex<<endl;

Roll No: 1234


Branch: CSE
Enter the marks scored in Subject 1: 75

cout<<Age:<<age<<endl;

Enter the marks scored in Subject 2: 78

Game Score: 85

};
class Student : public person

//Intermediate derived class

Sex: M

private:

Age: 20

int rollno;
char *branch;

Name: RAM

Roll No: 1234


Branch: CSE
Subject 1 Marks: 75

public:

Subject 1 Marks: 78

void read()

Total Marks: 153

Sports credit: 85

Person::read();
cout<<Roll No:;
cin>>rollno;
cout<<Branch:;
cin>>branch;
}
void display()
Prepared by A.V. KALPANA, Asst. ProfessorPage 21

CS6456 OBJECT ORIENTED PROGRAMMING


{
Person::display();
cout<<Roll No:<<rollno<<endl;
cout<<Branch:<<branch<<endl;
}
};
class Result: public Student
{
private:
int sub1, sub2;
public:
void read()
{
Student::read();
cout<<Enter the marks scored in Subject1:;
cin>>sub1<<endl;
cout<<Enter the marks scored in Subject2:;
cin>>sub2<<endl;
}
void display()
{
Student::display();
cout<<Subject1 Marks:<<sub1<<endl;
cout<<Subject2 Marks:<<sub2<<endl;
cout<<Total Marks:<<sub1+sub2<<endl;
}
};
Prepared by A.V. KALPANA, Asst. ProfessorPage 22

CS6456 OBJECT ORIENTED PROGRAMMING


class Sports
{
protected:
float score;
public:
void read()
{
cout<<Game Score:;
cin>>score;
}
void display()
{
cout<<"Sports credit:"<<score<<"\n";
}
};
class Result: public Exam, public Sports
{
public:
void read
{
Exam::read();
Sports::read();
}
void display()
{
Exam::display();
Sports::display();
Prepared by A.V. KALPANA, Asst. ProfessorPage 23

CS6456 OBJECT ORIENTED PROGRAMMING


}
};
void main()
{
clrscr();
Result r;
r.read();
r.display();
getch(); }

>>HIERARCHICAL INHERITANCE
Deriving two or more classes from a single base class is called as Hierarchical
inheritance.
Base classes

Derived classes

This contains one base class and more than one derived class.
class Base-class-name
{

};
class Derived-class-name1: visibility-mode Base-class-name
{
..
};
class Derived-class-nameN: visibility-mode Base-class-name
{
.
Prepared by A.V. KALPANA, Asst. ProfessorPage 24

CS6456 OBJECT ORIENTED PROGRAMMING


};

EXAMPLE
#include <iostream.h>
#include<conio.h>
class Person

//Base class

{
char *name;
char sex;
int age;
public:
void read()

OUTPUT:

Enter the Student's details:

cout<<Name:;

Name:Ajay

cin>>name;

Sex:M
Age:21

cout<<Sex:;

Print the Student's details:

cin>>sex;

Name:Ajay

cout<<Age:;

Sex:M

cin>>age;
}

Age:21
Enter the Employee's details:
Name:Vijay

void display()

Sex:M

Age:22

cout<<Name:<<name<<endl;

Print the Employee's details:

cout<<Sex:<<sex<<endl;
cout<<Age:<<age<<endl;

Name:Vijay
Sex:M
Age:22

}
Prepared by A.V. KALPANA, Asst. ProfessorPage 25

CS6456 OBJECT ORIENTED PROGRAMMING


};
class Student : public Person

//Intermediate derived class

{
public:
void read()
{
cout<<Enter the Students details:<<endl;
Person::read();
}
void display()
{
cout<<Print the Students details:<<endl;
Person::display();
}
};
class Employee : public Person{
public:
void read()
{
cout<<Enter the Employees details:<<endl;
Person::read();
}
void display()
{
cout<<Print the Employees details:<<endl;
Person::display();
}
Prepared by A.V. KALPANA, Asst. ProfessorPage 26

CS6456 OBJECT ORIENTED PROGRAMMING


};
void main()
{
Student s;
s.read();
s.display();
Employee e;
e.read();
e.display();
getch(); }

>>VIRTUAL BASE CLASS (OR) MULTIPATH INHERTANCE(OR) DIAMOND INHERITANCE

Consider a situation where three kinds of inheritance such as multiple, multilevel

and hierarchical inheritance are involved.


Derivation of class form another derived classes, which are derived from the same
base class is called as multipath inheritance. The following figure depicts
multipath inheritance.

A
B

Multipath
Inheritance
The syntax for the above hierarchy of inheritance
is
Class A
{ };
Class B:public A
{ };
Class C:public A
D

Prepared by A.V. KALPANA, Asst. ProfessorPage 27

CS6456 OBJECT ORIENTED PROGRAMMING

{ };
Class D:public B,public C
{ };
In this hierarchy, the class D has two direct base classes B and C, which has the

common base class A.


Class D inherits the properties of Class A via two separate paths.
Class A is called as indirect base class.
The public and protected members of Class A are inherited to class D twice, first

via class B and then via class C.


So class D have duplicate copy of the class A members which leads to error due to

compilation.
The duplication of the inherited members due to these multiple paths can be
avoided by making the common base class(class A) as the virtual base class while
declaring the direct or intermediate base class. The syntax to achieve virtual base
class concept is given as follows:
Class A
{ };
Class B: virtual public A
{ };
Class C: public virtual A
The keywords virtual and
{ };
public may be used in either
Class D: public B, public C
{
/*Only one copy of A will be inherited and the single copy will be shared by class
B & class C, since the common base class is made virtual*/
};

When a class is made a virtual base class, only one copy of that class is
inherited and shared by the derived classes, regardless of the number of
inheritance paths exists between Virtual base class and the derived class.

EXAMPLE
#include<iostream.h>
#include<conio.h>
class A
{
public:
int i;
};

// Class A is made virtual

Prepared by A.V. KALPANA, Asst. ProfessorPage 28

CS6456 OBJECT ORIENTED PROGRAMMING


class B : virtual public A
{
public:
int j;
};
class C: virtual public A
{
public:
int k;
};
class D: public B, public C
{
public:
int sum;
};

OUTPUT:
Value of i is : 10
Value of j is : 20
Value of k is :30
Sum is : 60

void main()
{
clrscr();
D ob;

// object is created for the finally derived class.

ob.i = 10; //Does not cause error, since only one copy of i is inherited by D
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
cout <<"Value of i is : "<< ob.i<<"\n";
cout <<"Value of j is : "<< ob.j<<"\n";
cout <<"Value of k is :"<< ob.k<<"\n";
cout <<"Sum is : "<< ob.sum <<"\n";
getch();
}
=====================================================================
RUN TIME POLYMORPHISM

Prepared by A.V. KALPANA, Asst. ProfessorPage 29

CS6456 OBJECT ORIENTED PROGRAMMING

Polymorphism is one of the OOPs feature which means, one name, multiple
forms.
The classification of polymorphism can be given as follows:

Compile time polymorphism

The compile time polymorphism can also be called as static binding or early
binding. This is implemented using the overloaded functions and operators.
The corresponding member function is selected by matching the arguments, type
of the argument and number of arguments.
This information is known to the compiler at the time of compiling the program.
So, this is called as Compile Time polymorphism.

Run time polymorphism

The run-time polymorphism can also be called as dynamic binding or late binding.
This is implemented using Virtual functions.
When the same function with the same prototype is declared both in the base
class and derived class, it is called as function overriding.
The appropriate member function could be selected at the time of running the
program. So, this is called as Runtime polymorphism.

>>VIRTUAL FUNCTIONS
In virtual functions, the pointer to the base class is used to refer to all the
derived class objects.
The class that contains a virtual function is called as the polymorphic class.
Eventhough, a base pointer is made to contain the address of the derived class
object; it always executes the function in the base class.
Prepared by A.V. KALPANA, Asst. ProfessorPage 30

CS6456 OBJECT ORIENTED PROGRAMMING


This is because, the compiler simply ignores the contents of the pointer(i.e The
address of the object pointed by the pointer is ignored) and chooses the member
function that matches the type of the pointer(i.e. The base class pointer).
EXAMPLE
#include <iostream.h>
#include<conio.h>
class Shape
{
public:
virtual void draw ()
{
cout<< I am a Shape<< endl;
}
};
class Circle: class Shape
{
public:
virtual void draw ()
{
cout<< I am a Circle<< endl;
}
};
void main ()
{

OUTPUT:
I am a Shape

Shape *ptrs, s;
Circle c;
ptrs=&s;
ptrs draw();
Prepared by A.V. KALPANA, Asst. ProfessorPage 31

I am a Circle

CS6456 OBJECT ORIENTED PROGRAMMING


ptrs=&c;
ptrs draw();
}
***NOTE:

Without mentioning the base class function as virtual, the output will be

I am a Shape
I am a Shape
Instead of
I am a Shape
I am a Circle
This is because the base classs function would be repeatedly called, as the base pointer
executes the function in the base class.

If the function in the base class is designated as virtual , then the derived classs
function would be called. If it is not virtual, the base classs function would be
called.

/* Refer the rules for virtual functions in book*/


>>PURE VIRTUAL FUNCTION

The pure virtual function (or abstract function) is a virtual function which does not

have a function definition. The function is assigned to the value 0.


0 is appended to the virtual function instead of specifying an implementation for
the function.

Syntax:
Virtual return_type function_name()=0;
class A //Abstract class
{
public:
virtual void func() = 0; // pure virtual function
};

Prepared by A.V. KALPANA, Asst. ProfessorPage 32

CS6456 OBJECT ORIENTED PROGRAMMING


class B: public A
{
public:
void func() // overriding the pure virtual function &amp; implementing it
{
cout << "Class B";
}
};
class C: public B
{
public:
void func() // implementing the pure virtual function
{
cout << "Class C";
}
OUTPUT:
};
void main()

Class A
Class C

{
B b;
C c;
A *x = &b;
A *y = &c;
x func();
yfunc();
}
>>RULES FOR PURE VIRTUAL FUNCTION

1. The virtual function must be member of class


2. They cannot be static members
3. They are accessed by using object pointers
4. Prototype of base class function & derived class must be same
5. Virtual function in base class must be defined even though it is not used
6. A virtual function can be friend function of another class
7. We could not have virtual constructor
8. If a virtual function is derived in base class, it need not be necessarily redefined in the
derived class
9. Pointer object of base class can point to any object of derived class but reverse is not
true
Prepared by A.V. KALPANA, Asst. ProfessorPage 33

CS6456 OBJECT ORIENTED PROGRAMMING


10. When a base pointer points to derived class, incrementing & decrementing it will not
make it point to the next object of derived class
=====================================================================
ABSTRACT CLASS

A class contains a pure virtual function is declared as abstract class.


Objects cannot be created for an abstract class.
There is no implementation for an abstract class.
The abstract class should be inherited.
The pure virtual function (or abstract function) is a virtual function which does not

have a function definition. The function is assigned to the value 0.


0 is appended to the virtual function instead of specifying an implementation for
the function.

Syntax:
Virtual return_type function_name()=0;
class A //Abstract class
{
public:
virtual void func() = 0; // pure virtual function
};
class B: public A
{
public:
void func() // overriding the pure virtual function & implementing it
{
cout << "Class B";
}
};
OUTPUT:

class C: public B
{
public:
Prepared by A.V. KALPANA, Asst. ProfessorPage 34

Class A
Class C

CS6456 OBJECT ORIENTED PROGRAMMING


void func() // implementing the pure virtual function
{
cout << "Class C";
}
};
void main()
{
B b;
C c;
A *x = &b;
A *y = &c;
x func();
yfunc();
}
Characterisitics of Abstract class:
Abstract class cannot be instantiated but pointers and references of abstract class
type can be created.
Abstract class can have normal functions and variables along with a pure virtual
function.
Abstract class are mainly used for upcasting, so that its derived classes can use its
interface
Classes inheriting an abstract class must implement all pure virtual functions, or
else they will become abstract too.
=====================================================================
EXCEPTION HANDLING
Exceptions
Exceptions are runtime anamolies or unusual conditions that a program may encounter
while executing

Prepared by A.V. KALPANA, Asst. ProfessorPage 35

CS6456 OBJECT ORIENTED PROGRAMMING

Exception Handling
The process of catching and handling exceptions is known as exception handling.

The exception handling mechanism suggests a separate error handling code that performs
the following tasks:
1. Find the problem(Hit the exception)
2. Inform that the error has occurred(Throw the exception)
3. Receive the error information(Catch the exception)
4. Take corrective actions(Handle the exception)

An Exception is an object. It is sent from the part of the program where an error occurs
to that part the program which is going to control the error.
There are two types of exceptions,

Synchronous Exceptions,

Asynchronous Exceptions.

Synchronous Exception: An error such as out of range or overflow belongs to it.


Asynchronous Exception: Errors that are occurred by the events beyond the control of
program such as keyboard interrupts are belong to this exception.
The Error Handling code consists of two segments, one to detect errors and to throw the
exceptions and other to catch the exceptions and to take appropriate actions.

Prepared by A.V. KALPANA, Asst. ProfessorPage 36

CS6456 OBJECT ORIENTED PROGRAMMING


Exception handling mechanism is built on three 3 keywords to handle exception. They
are try, catch and throw block.

try: try block is identified by a block of statement. The try block is indicated by try
keyword followed by block of statements enclosed in braces. The main purpose of this
block is to generate an exception.

throw: when an exception has been detected in the try block it is thrown by throw
keyword in the try block.

catch: catch block identifies catching an exception. Catch block catches the exception
thrown by the throw statement in the try block. A catch block begins with keyword catch
with parenthesis which says the type of exception to which it has to act.

Fig. The block throwing exception


Syntax:
Prepared by A.V. KALPANA, Asst. ProfessorPage 37

CS6456 OBJECT ORIENTED PROGRAMMING


try
{
..
throw exception; // statement to detect and throw exception//
.
}
catch (data type arg) //statement to handle exception//
{
.}
Catch block
A catch block looks like a functio definition and is of the form:
Syntax:
catch(type arg)
{
..

}
The type indicates the type of exception that catch block handles. The parameter arg is
optional parameter name.
The catch statement catches an exception whose type matches with the type of catch
argument. When it is caught, the code in the catch block is executed.
If the parameter in the catch statement is named, then the parameter can be used in the
exception-handling code. After executing the handler, the control goes to the statement
immediately following the catch block.
Due to mismatch if an exception is not caught, abnormal program termination will occur.
***Note: The catch block is simply skipped if the catch statement does not catch an
exception.
Throw Mechanism

Prepared by A.V. KALPANA, Asst. ProfessorPage 38

CS6456 OBJECT ORIENTED PROGRAMMING


When an exception is desired to be handled is detected, it is thrown using the throw
statement in one of the following forms:
throw(exception);
throw exception;
throw;
The operand object exception may be of any type, including constants. It is also possible
to throw objects not intended for error handling.
When an exception is thrown, it will caught by the catch statement associated with the try
block. That is, the control exits the current try block, and is transferred to the catch block
after that try block.
Throw point can be in a deeply nested scope within a try block or in a deeply nested
function call. In any case, control is transferred to the catch statement.
Example
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
float d;
clrscr();
cout<<"Enter the value of a:--";
cin>>a;
cout<<"Enter the value of b:--";

OUTPUT:
RUN 1

cin>>b;

Enter the value of a:--40

cout<<"Enter the value of c:--";

Enter the value of b:--20

cin>>c;

Enter the value of c:--80

try
{
if((a-b)!=0)

Result is equal to: 4


RUN2
Enter the value of a:--20

{
d=c/(a-b);

Enter the value of b:--20

Enter
Prepared by A.V. KALPANA, Asst. ProfessorPage
39the value of c:--40
Answer is infinite because a-b is: 0

CS6456 OBJECT ORIENTED PROGRAMMING


cout<<"Result is equal to:"<<d;
}
else
{
throw(a-b);
}
}
catch(int i)
{
cout<<"Answer is infinite because a-b is:"<<i;
}
getch();
}
FUNCTION INVOKED BY TRY BLOCK THROWING EXCEPTION
Most often exceptions are thrown by functions that are invoked from within the try
block. The point at which the throw is executed is called throw point. Once an exception
is thrown to the catch block, control cannot return to the throw point.

type function(arg-list)
//function with exception
{

throw(object);
//throws exception
..
}
.
.
tryFunction invoked by try block throwing exception
Fig.
{
Syntax:
..
..
//invoke function here
..
}
catch(type arg)
//Catches exception
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 40
.
//Handles exception here
.
}

CS6456 OBJECT ORIENTED PROGRAMMING

RETHROWING AN EXCEPTION
A handler may decide to re-throw an exception caught without processing it. In such
situations, we may simply invoke throw without any arguments as shown below:
throw;
This causes the current exception to be thrown to the next enclosing try/catch sequence
and is caught by a catch statement listed after that enclosing try block. The following
program demonstrates how an exception is re-thrown and caught.
Example: Program to illustrate re-throwing of exception
#include<iostream.h>
void divide(int x, double y)

OUTPUT:
Inside main

{
cout<<"Inside function"<<endl;

Inside function
Division=5.25

try

End of function

Inside function
Caught double inside function

Caught double inside main


Prepared by A.V. KALPANA, Asst. ProfessorPage 41
End of main

CS6456 OBJECT ORIENTED PROGRAMMING


if(y == 0.0)
throw y;
else
cout<<"Division = "<<x/y<<"\n";
}
catch(double)
{
cout<<"Caught double inside function"<<endl;
throw;
}
cout<<" End of function<<endl;
}
void main()
{
cout<<"Inside main"<<endl;
try
{
divide(10.5,2.0);
divide(20.5,0.0);
Prepared by A.V. KALPANA, Asst. ProfessorPage 42

CS6456 OBJECT ORIENTED PROGRAMMING


}
catch(double)
{
cout<<"Caught doubling inside main"<<endl;
}
cout<<"End of main"<<endl;
}

4.Explain the following concepts with examples


(i)Multiple catch
(ii)Exception specification
(i)Multiple Catch
It is possible that a program segment has more than one condition to throw an exception.
In such cases, we can associate more than one catch statement with a try as shown below:
try
{
..
}
catch(type1 arg)
{
..
}
catch(type 2 arg)
{
..
Prepared by A.V. KALPANA, Asst. ProfessorPage 43

CS6456 OBJECT ORIENTED PROGRAMMING


}
Example
#include<iostream.h>
#include<conio.h>
void test(int x)
{
try
{
if(x>0)
throw x;
else
throw 'x';
}
catch(int x)
{
cout<<"Catch a integer and that integer is:"<<x<<endl;
}
catch(char x)
{
cout<<"Catch a character and that character is:"<<x<<endl;
}
}
void main()
{
clrscr();
cout<<"Testing multiple catches \n:";
test(10);

OUTPUT:
Testing multiple catches
Catch a integer and that integer is: 10
Catch a character and that character is: x

Prepared by A.V. KALPANA, Asst. ProfessorPage 44

CS6456 OBJECT ORIENTED PROGRAMMING


test(0);
getch();
}
(ii)Exception Specification
This can be used to throw only the specified exception using a throw list
condition.
Syntax:
data-type function_name (parameter list) throw (data type list)
{
statements1;
statements2;
}
The Format for this is,
The data type list indicates the type of exceptions to be thrown.

If the user wants to deny a function from throwing exception then the user can declare
data type list as void.
throw (); // void or vacant list
Program to restrict a function to throw only specified type of exceptions:
void check (int k) throw (int, double)
{
if (k == 1) throw k;
else if (k ==2) throw k;
else if (k ==-2) throw 1.0;
cout<< End of Function Check();
}
void main ()
{
try
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 45

OUTPUT:
K ==1
Caught a Char Exception
End of main

CS6456 OBJECT ORIENTED PROGRAMMING


cout<< k == 1;
check(1);
cout<< k ==2;
check(2);
cout<< k == -2;
check(-2);
}
catch ( char g)
{
cout<< Caught a Char Exception;
}
catch ( int j)
{
cout<< Caught a Integer Exception;
}
catch ( double s)
{ cout<< Caught a Double Exception;}
cout<< End of main;
}
UNCAUGHT EXCEPTIONS
C++ having two functions to control uncaught exceptions.
a. Terminate () Function
b. set_terminate () Function
c. Unexpected() Function
d. set_unexpected() Function
Terminate () Function:
If the exception handler is not defined, while the exception is thrown then the Terminate
() function is invoked. Implicitly the abort () function is invoked.
Program to catch uncaught exceptions:
class one { };
Prepared by A.V. KALPANA, Asst. ProfessorPage 46

CS6456 OBJECT ORIENTED PROGRAMMING


class two { };
void main ()
{
try
{

OUTPUT:
An uncaught exception
Abnormal program execution

cout << An uncaught exception;


throw two ();
}
catch (one)
{
cout << Exception for one;
}
}
Set_Terminate () Function:
The Set_Terminate () function is used to transfer the control to specified error handling
function. This function requires only one argument which is the function name. It returns
nothing. When no function is specified, the program is terminated by an implicit call to
abort () function.
Program to demonstrate set_terminate () function:
class one { };
class two { };
void MyTerminate()
{
cout << MyTerminate is invoked;
exit(1);
}
void main ()
{
set_terminate (MyTerminate);
try

OUTPUT:
Throwing exception

is invoked
Prepared by A.V. KALPANA, Asst. ProfessorPageMyTerminate
47

CS6456 OBJECT ORIENTED PROGRAMMING


{
cout << Throwing exception;
throw two();
}
catch (one)
{
cout << Exception for one;
} //At this point function MyTerminate is invoked
}
Unexpected() Function
The unexpected function is called when a function throws an exception not listed in its
exception specification. The program calls unexpected() which calls any user-defined
function registered by set_unexpected. If no function is registered with set_unexpected,
the unexpected() function then invokes the terminate() function.
Syntax:
void unexpected();
Example
class zero{};
void test(int num) throw()

OUTPUT:

RUN 1

if(num>0)

Enter any number: 10

cout<<positive number<<endl;
else
if(num<0)

Positive number
End of main

cout<<Negative number<<endl;

RUN 2

else

Enter any number:-1

throw zero();

Negative number

}
void main()
{

End of main
RUN 3

Enter any number: 0


Prepared by A.V. KALPANA, Asst. ProfessorPage 48
Abnormal program termination

CS6456 OBJECT ORIENTED PROGRAMMING


int num;
cout<<Enter any number:;
cin>>num;
try
{
test(num);
}
catch()
{
cout<<Catch all Exceptions;
}
cout<<endl<<End of main;
}
set_unexpected()
The function set_unexpected() allows the user to install a function that defines the
programs actions to be taken when a function throws an exception not listed in its
exception not listed in its exception specification. By default, an unexpected exception
causes unexpected() to be called, which in turn calls unexpected_func().
Example
class zero{};

OUTPUT:

void test(int num) throw()

RUN 1

Enter any number: 10

if(num>0)
cout<<positive number<<endl;
else

Positive number
End of main

if(num<0)

RUN 2

cout<<Negative number<<endl;

Enter any number:-1

else

Negative number

throw zero();
}
void MyUnexpected()

End of main
RUN 3

Enter any number: 0


Prepared by A.V. KALPANA, Asst. ProfessorPage 49
MyUnexpected is invoked

CS6456 OBJECT ORIENTED PROGRAMMING


{
cout<<MyUnexpected is invoked<<endl;
}
void main()
{
int num;
cout<<Enter any number:;
cin>>num;
set_unexpected(MyUnexpected);
try
{test(num);}
catch()
{
cout<<Catch all Exceptions;
}
cout<<endl<<End of main;
}
=====================================================================
GENERIC PROGRAMMING

Templates enable to define generic classes and functions and thus support generic

programming.
Generic programming is an approach where generic types are used as

parameters, so that they can work for a variety of suitable data types.
A template can be used to create a family of classes or functions.

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.

Prepared by A.V. KALPANA, Asst. ProfessorPage 50

This

approach,

pioneered

CS6456 OBJECT ORIENTED PROGRAMMING


by Ada in 1983, permits writing common functions or types that
differ only in the set of types on which they operate when used,
thus reducing duplication.
Software entities created using generic programming are known
as generics in Ada, Eiffel, Java, C#,

and Visual

Basic

.NET; parametric polymorphism in ML, Scala (possibly the only


modern

language

that

supports

both

parameterized

types

originating from functional languages and virtual types from the


OO paradigm) and Haskell (the Haskell community also uses the
term

"generic"

for

related

concept); templates in C++;

but

somewhat

and parameterized

different

types in

the

influential 1994 book Design Patterns.


The

authors

of Design

Patterns note

that

this

technique,

especially when combined with delegation, is very powerful but


that "Dynamic, highly parameterized software is harder to
understand than more static software."
Generic

programming

certain statically

typed

refers

to

programming

features

of

languages that

allow some code to effectively refine the static type


system.
For instance in C++, a template is a routine in which some
parameters

are

qualified

by

type

variable.

Since

code

generation in C++ depends on concrete types, the template is


specialized for each combination of argument types that occur at
some instantiation.
Prepared by A.V. KALPANA, Asst. ProfessorPage 51

CS6456 OBJECT ORIENTED PROGRAMMING


Generic programming is used to implement the STL libraries to
define containers,

iterators,

and

algorithms.

Examples

of

containers are vectors, queues, sets, maps, and lists and hash
tables and functions such as a particular sorting algorithm for
objects specified in terms more general than a concrete type.

Generic

programming

pioneer Alexander

Stepanov wrote:

"Generic programming is about abstracting and classifying


algorithms and data structures. It gets its inspiration from
Knuth and not from type theory. Its goal is the incremental
construction of systematic catalogs of useful, efficient and
abstract algorithms and data structures.
***PARAMETERIZING THE CLASS
Templates are sometimes called as parameterized classes as templates are defined with a
parameter that would be replaced by a specific data type.
***CLASS TEMPLATE:
Definition:
The template that allows us to define generic classes is called as class template. Using
class template, a family of classes that contains the data members and member functions
of different data types can be defined. The general format of a class template is:
Syntax:
template<class T>
class class_name
{
/* Class member specification with anonymous type T wherever appropriate*/
}
Syntax to invoke the class

Prepared by A.V. KALPANA, Asst. ProfessorPage 52

CS6456 OBJECT ORIENTED PROGRAMMING


Classname <datatype> objectname;
EXAMPLE FOR CLASS TEMPLATE WITH ONE ARGUMENT
//To add two numbers of the same type using class template//
#include<iostream.h>
#include<conio.h>
template<class T>

// Template declaration with one generic type T

class add
{
T a,b,c;

// Data member declaration with type T

public:
void getdata(T x, T y)

// Function definition with template type arguments

{
a=x;
b=y;
}
void display()
{
c=a+b;
cout<<c<<endl;
}
};
void main()
{
clrscr();
add <int> obj1;
cout<<"Sum of integers:";
obj1.getdata(5,4);
obj1.display();
add <float> obj2;
cout<<"Sum of float type:";
obj2.getdata(1.5,3.1);

OUTPUT:
Sum of integers: 9

Prepared by A.V. KALPANA, Asst. ProfessorPage 53

Sum of float type: 4.6

CS6456 OBJECT ORIENTED PROGRAMMING


obj2.display();
getch();
}
In this program,

The statement, add <int> obj1; Invoke the class template with datatype int. i.e

all the template type variables and arguments(T) are replaced with integer type.
The statement, add <float> obj2; Invoke the class template with datatype float.
i.e all the template type variables and arguments(T) are replaced with float type

***CLASS TEMPLATE WITH MULTIPLE ARGUMENTS


Definition:

More than one generic datatype can be used in a class template. They are
declared as a comma-seperated list within the template specification

Syntax:
template< class T1, class T2,>
class class_name
{
/* Class member specification with anonymous types T1 & T2 wherever appropriate*/
}
Syntax to invoke the class
Classname <datatype1, datatype2,> objectname;
EXAMPLE
#include<iostream.h>
#include<conio.h>
template<class T1, class T2>
class test
{
T1 a;

/* Data member declaration with types T1 and T2*/

T2 b;
public:
test(T1 x, T2 y)

/* Function definition with template type arguments T1,T2*/

Prepared by A.V. KALPANA, Asst. ProfessorPage 54

CS6456 OBJECT ORIENTED PROGRAMMING


{
a=x;
b=y;
}
void show()
{
cout<<"a & b="<<a<<","<<b<<endl;
}
};
void main()
{
clrscr();
test <int, float> obj1(123,1.23);

OUTPUT:

test<int,char> obj2(100,'K');

a & b values are: 123,1.23

obj1.show();
obj2.show();

a & b values are: 100,K

getch();
}
In this program,

The statement, test <int, float> obj1(123,1.23); Invokes the class template by
replacing the first template type (T1) by int type and the second template type

(T2) by the float type


The statement, test<int,char> obj2(100,'K'); Invokes the class template by
replacing the first template type (T1) by int type and the second template type
(T2) by the char type

***FUNCTION TEMPLATE
Definition:
Function templates can be used to create a family of functions with different
argument types.
Syntax:
template<class T>
Prepared by A.V. KALPANA, Asst. ProfessorPage 55

CS6456 OBJECT ORIENTED PROGRAMMING


returntype functionname(arguments of type T)
{
/* Body of the function with type T wherever appropriate*/

EXAMPLE PROGRAM FOR FUNCTION TEMPLATE WITH ONE ARGUMENT


1) Program to swap two values
#include<iostream.h>
#include<conio.h>
template<class S>
void swap(S &x, S &y) // Function declaration with template type arguments
{
S t;

//Temporary variable declaration of type T

t=x;
x=y;
y=t;
}
void main()
{
clrscr();
char ch1,ch2;
cout<<"Enter the characters to swap"<<endl;
cin>>ch1>>ch2;
swap(ch1,ch2);

OUTPUT:

cout<<"After swapping"<<endl;

Enter the characters to swap


a
b
After swapping
ba
Enter the integers to swap
1
2
After swapping
21

cout<<ch1<<" "<<ch2<<endl;
int a,b;
cout<<"Enter the integers to swap"<<endl;
cin>>a>>b;
swap(a,b);
cout<<"After swapping"<<endl;
cout<<a<<" "<<b<<endl;
getch();
Prepared by A.V. KALPANA, Asst. ProfessorPage 56

CS6456 OBJECT ORIENTED PROGRAMMING


}
In this program,

The statement, swap(ch1,ch2); Invokes the function template by replacing the

template datatype(T) to the char datatype.


The statement, swap(a,b); Invokes the function template by replacing the
template datatype(T) to the int datatype.

*** FUNCTION TEMPLATE WITH MULTIPLE ARGUMENTS


Definition:
More than one generic data type can be used in the function template using a commaseparated list.
Syntax:
template<class T1, class T2,>
Returntype functionname(arguments of types T1 and T2)
{
//Body of the function

EXAMPLE
#include<iostream.h>
#include<conio.h>
template<class T1,class T2> // Template declaration with two arguments.
void display(T1 x, T2 y) //Function definition with template type arguments T1,T2.
{
cout<<x<<" "<<y<<"\n";
}
void main()
{
clrscr();
display(100,"ABC");
display(12.34, 123);
getch();
}
In this program,
Prepared by A.V. KALPANA, Asst. ProfessorPage 57

OUTPUT:
100 ABC
12.34 123

CS6456 OBJECT ORIENTED PROGRAMMING

The statement, display(100,"ABC"); invokes the function template by replacing


the first template type in the argument (T1) by int datatype and the second

template type in the argument (T2) by the string datatype


The statement, display(12.34,123); invokes the function template by replacing
the first template type in the argument(T1) by float datatype and the second
template type in the argument (T2) by the int type.

*** MEMBER FUNCTION TEMPLATES


Defintion:
When a class is defined, the member functions of the class can also be defined outside
the class. The member function templates can be used for this purpose.
Syntax:
template<class T>
returntype classname <T> :: functionname(arglist)
{
//Function body;
}
EXAMPLE
#include<iostream.h>
#include<conio.h>
template<class T>
class add
{
T a,b,c;
public:
void getdata(T x, T y);

//Member function declaration inside class

void display()
{
c=a+b;
cout<<c<<endl;
}
Prepared by A.V. KALPANA, Asst. ProfessorPage 58

CS6456 OBJECT ORIENTED PROGRAMMING


};
/* Defining member function outside class using member function template*/
template<class T>
void add <T>::getdata(T x, T y)

/*Member function template*/

{
a=x;
b=y;
}
void main()
{
clrscr();
add <int> obj1;
cout<<"Sum of integers:";
obj1.getdata(5,4);
obj1.display();

OUTPUT:

add <float> obj2;

Sum of integers: 9

cout<<"Sum of float type:";


obj2.getdata(1.5,3.1);

Sum of float type: 4.6

obj2.display();
getch(); }
In this program,

The statement, obj1.getdata(5,4); Invoke the member function template by

replacing the template datatype (T) by int datatype.


The statement, obj2.getdata(1.5,3.1); Invoke the member function template by
replacing the template datatype(T) by float datatype.

2. Explain in detail about Non-type template arguments and overloading of template


functions.
***NON-TYPE TEMPLATE ARGUMENTS

A template with multiple arguments can also have the non-type arguments, which
means, in addition to the type argument T, the other arguments such as strings,

Prepared by A.V. KALPANA, Asst. ProfessorPage 59

CS6456 OBJECT ORIENTED PROGRAMMING


function names, constant expressions, built-in datatypes can be used. For
example:
template<class T, int size>
class array
{
T a[size];

//automatic array initialization

..
};
This template supplies the size of the array as an argument(non-type). The arguments
must be created when the template class is created.
Eg: array<int, 5> a1;

// Initializes an array of 5 integers.

array<char,20> a2; // String of size 20


Example program for Template class with non-generic arguments
#include<iostream.h>
#include<conio.h>
template<class T, int n>
class Sample
{
public:
void print(T x);
};
template<class T, int n>::print(T x)
{
for(int i=0; i<n; i++)
{
cout<<x<<\t;
}
}
void main()
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 60

OUTPUT:
5

CS6456 OBJECT ORIENTED PROGRAMMING


Sample<int, 3> s1;
s1.print(5);
Sample<char, 5> s2;
s1.print(A);
}
*** OVERLOADING OF TEMPLATE FUNCTIONS
A template function may be overloaded either by template functions or ordinary
functions.
EXAMPLE
#Iinclude<iostream.h>
#include<conio.h>
template<class T>
void display(T x)
{
cout<<Template Display:<<x<<\n;
}
void display(int x)

// Overloads the generic display() function

{
cout<<Explicit Display:<<x<<\n;

OUTPUT:

Explicit Display: 100

void main()
{
clrscr();

Template Display: 12.34


Template Display: C

display(100);
display(12.34);
display(C);
getch();
}
In this program, the call display (100) invokes the ordinary version of display() and not
the template version.
Prepared by A.V. KALPANA, Asst. ProfessorPage 61

CS6456 OBJECT ORIENTED PROGRAMMING


=====================================================================
STANDARD TEMPLATE LIBRARY (STL)

The Standard Template Library (STL) is an exemplary framework that is built on

the foundations of generic programming.


STL is a collection of generic algorithms and containers that communicate through

iterators.
STL is different from normal libraries. All other libraries defined need entities as

classes.
The operations required in that class are written as member functions of the class.
But STL has number of non member functions designed to work on multiple classes
of container classes.

The standard template library (STL) contains


o Containers
o Algorithms
o Iterators

A container is an object that actually stores data. It is a way that stored data is
organized in memory, for example an array of elements.

Algorithms are procedures that are applied to containers to process the data, for
example search for an element in an array, or sort an array. Algorithms are
implemented by template functions.

Iterators is an object(like a pointer), that points to an element in a container, for


example you can increment an iterator to point to the next element in an array

1.Containers
Prepared by A.V. KALPANA, Asst. ProfessorPage 62

CS6456 OBJECT ORIENTED PROGRAMMING

The generic software component used in STL is called containers.


They can able to contain objects within themselves.
Containers are of two types:
o Sequence Containers
o Sorted Associative Containers
o Derived Containers

(1) Sequence Containers


Store elements in a linear sequence, like a line
Each element is related to other elements by its position along the line.
They all expand themselves to allow insertion of elements and all of them
support a number of operations on them.

Elements in all these containers are accessed using an iterator.


Some of the sequence containers are:
Vector
List
Deque

Comparison of Sequence Containers

(2)Sorted Associative Containers


o They are designed to support direct access to elements using keys.
Prepared by A.V. KALPANA, Asst. ProfessorPage 63

CS6456 OBJECT ORIENTED PROGRAMMING


o They are not sequential.
o It keeps them sorted irrespective of insertions and deletions taking place on
them.
o Some of the sorted associative containers are:
Map
Multimap
Set
Multiset
o All these containers store data in a structure called tree which facilitates
fast searching, deletion and insertion.
o However, these are very slow for random access and inefficient for sorting.
(3)Derived Containers

These are also known as container adaptors


The derived containers do not support iterators and therefore we cannot use them

for data manipulation.


They support two member functions pop() and push() for implementing deleting
and inserting operations.

STL Containers
Header

Contents

<vector>

An array of T

<list>

A doubly-linked list of T

<deque>

A double-ended queue of T

<queue>

A queue of T

<stack>

A stack of T

<map>

An associative array of T

<set>

A set of T

<bitset>

A set of Boolean values

Difference between sequence and sorted associative container


Sequence container
Sorted associative container
Sequence container are able to hold Sorted associative container are able to
elements

in

an

unordered

form

as hold elements in an ordered form.

inserted.
Element is accessed by index or position of Element is accessed by the value of key
the element.

which is part of the element

Prepared by A.V. KALPANA, Asst. ProfessorPage 64

CS6456 OBJECT ORIENTED PROGRAMMING

Advantages of using containers


1. Small in number: They are few and so are easy to master
2. Generality: They are general in nature.
3. Automatically adjusting growth: The storage requirements for the components
can be dynamic.
4. Similar behavior to built in types: STL container can be defined like a normal
object, can be assigned or copied to another container and so on.
5. Extensibility: New algorithm can be added to existing container.
6. These software components are Efficient, Tested, Debugged and Standardized.
7. They are portable and reusable.
2.Algorithms
STL generic algorithms can be applied to a sequence of elements. They are defined in the
following header file.
STL Algorithms
Header

Contents

<algorithm>

A collection of generic algorithms

Advantages of using algorithms


Programmers are freed from writing routines like sort(), merge(), find() etc. with
different variations.

They are readymade from STL


They are efficient
They are standard
Easy to learn

3.Iterators
Iterators are like pointers and can be used to traverse and list out container contents.
They are defined in the following header file.
STL Iterators
Header

Contents

<iterator>

Various types of iterators and iterator support

Prepared by A.V. KALPANA, Asst. ProfessorPage 65

CS6456 OBJECT ORIENTED PROGRAMMING

Numeric Library
STL provides several classes and algorithms that are specifically designed for numeric
computations
Numeric Containers and Algorithms
Header

Contents

<complex>

Complex numbers and their associated operations

<valarray>

Mathematical vectors and their associated operations

<numerics>

Generalized numeric operations

Utilities
The following headers define auxiliary components that are used in STL containers and
algorithms. These include function adaptors, pairs, and class auto_ptr.
General Utilities
Header

Contents

<utility>

Operators and pairs

<functional>

Function objects

<memory>

Allocators and auto_ptr

WORKING PRINCIPLE OF STL


CONTAINERS

They are objects that contain other objects


They are two types namely,
o Sequence Containers
o Sorted Associative Containers

Sequence Containers
The sequence containers store the elements in a sequence. Some of them are vector,
deque and list.
Vector
Prepared by A.V. KALPANA, Asst. ProfessorPage 66

CS6456 OBJECT ORIENTED PROGRAMMING


o It is the most widely used container
o It stores elements in contiguous memory locations and enable direct access to any
element using the subscript operator [ ].
o A vector can change its size dynamically and therefore allocates memory as
needed at run time.

v.pop_back();

#include<vector>
#include<string>
#include<iostream>
class Student
{
int rollno;
string name;
public:
Student(){}
Student(int trollno, string tname)
Prepared by A.V. KALPANA, Asst. ProfessorPage 67

CS6456 OBJECT ORIENTED PROGRAMMING


{
rollno=trollno;
name=tname;
}
friend ostream &operator <<(ostream &tempout, Student tstudent)
{
return tempout<<tstudent.rollno<<\t<<tstudent.name<<endl;
}
};
void main()

OUTPUT:

vector<int> vi;

11

vi.push_back(11);
vi.push_back(12);
vector<int>::iterator intindex;
for(intindex=vi.begin();intindex<vi.end(); intindex++)

12
1234

AAA

4567

BBB

{
cout<<*intindex<<endl;
}
vector<Student>vs;
Student s1(1234, AAA);
Student s2(4567, BBB);
vs.push_back(s1);
vs.push_back(s2);
vector<Student>::iterator StudentIndex;
for(StudentIndex=vs.begin(); StudentIndex!=vs.end();StudentIndex++)
{
cout<<*StudentIndex<<endl;
}
}
List
Prepared by A.V. KALPANA, Asst. ProfessorPage 68

CS6456 OBJECT ORIENTED PROGRAMMING

An STL list container is a double linked list, in which each element contains a pointer
to its successor and predecessor.

It supports a bidirectional, linear list and provides and efficient implementation for
deletion and insertion operations.

Unlike a vector, which supports random access, a list can be accessed sequentially
only.

It is possible to add and remove elements from both ends of the list

Lists do not allow random access but are efficient to insert new elements and to sort
and merge lists

#include<list>
#include<string>
#include<iostream>
class Student
{
int rollno;
string name;
public:
Student(){}
Student(int trollno, string tname)
{
rollno=trollno;
name=tname;
}
friend ostream &operator <<(ostream &tempout, Student tstudent)
Prepared by A.V. KALPANA, Asst. ProfessorPage 69

CS6456 OBJECT ORIENTED PROGRAMMING


{
return tempout<<tstudent.rollno<<\t<<tstudent.name<<endl;
}
};
void main()
list<int>li;
li.push_back(11);
li.push_back(12);

OUTPUT:

list<int>::iterator intindex;

11

for(intindex=li.begin();intindex!=li.end();intindex++)

12

1234

AAA

4567

BBB

cout<<*intindex<<endl;
}
list<Student> ls;
Student s1(1234, AAA);
Student s2(4567, BBB);
ls.push_back(s1);
ls.push_back(s2);
list<Student>::iterator StudentIndex;

for(StudentIndex=ls.begin(); StudentIndex!=ls.end();StudentIndex++)
{
cout<<*StudentIndex;
}
}
Generic Algorithm: find() with list
#include<list>
#include<string>
#include<iostream>
class Student
{
int rollno;
Prepared by A.V. KALPANA, Asst. ProfessorPage 70

CS6456 OBJECT ORIENTED PROGRAMMING


string name;
public:
Student(){}
Student(int trollno, string tname)
{
rollno=trollno;
name=tname;
friend ostream &operator <<(ostream &tempout, Student tstudent)
{
return tempout<<tstudent.rollno<<\t<<tstudent.name<<endl;
}
bool operator = = (Student tstudent)
{
return (name==tstudent.name);
}
};
void main()
list<Student> ls;

OUTPUT:

Student s1(1234, AAA);

11

Student s2(1235, BBB);


Student s3(1236, CCC);

12
1234

AAA

1237

MMM

ls.push_back(s2);

1235

BBB

ls.push_back(s3);

1236

CCC

ls.push_back(s1);

list<Student>::iterator StudentIndex;
Student s4(1237, MMM);
StudentIndex=find(ls.begin(), ls.end(), s2);
ls.insert(StudentIndex, s4);
for(StudentIndex=ls.begin(); StudentIndex!=ls.end();StudentIndex++)
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 71

CS6456 OBJECT ORIENTED PROGRAMMING


cout<<*StudentIndex;
}
}
Deque

It is a useful container adapted into two other containers namely queue and stack.
Here push_front() is used to insert the elements
Deque is a structure where the insertion takes place at either the end or the begin

position.
The push_front() function adds the element in the beginning so that the data
entered is displayed in the reverse order.

#include<deque>
#include<string>
#include<iostream>
class Student
{
int rollno;
string name;
public:
Student(){}
Student(int trollno, string tname)
{
rollno=trollno;
name=tname;
}
friend ostream &operator <<(ostream &tempout, Student tstudent)
{
return tempout<<tstudent.rollno<<\t<<tstudent.name<<endl;
}
};
void main()
Prepared by A.V. KALPANA, Asst. ProfessorPage 72

CS6456 OBJECT ORIENTED PROGRAMMING


deque<Student> di;
di.push_front(11);
di.push_front(12);
deque<int>::iterator intindex;
for(intindex=di.begin();intindex<di.end();intindex++)
{
cout<<*intindex<<endl;
}
deque <Student>ds;

OUTPUT:

Student s1(1234, AAA);

12

Student s2(1235, BBB);


Student s3(1236, CCC);

11
1236

CCC

ds.push_front(s2);

1235

BBB

ds.push_front(s3);

1234

AAA

ds.push_front(s1);

deque<Student>::iterator StudentIndex;
for(StudentIndex=ds.begin(); StudentIndex!=ds.end();StudentIndex++)
{
cout<<*StudentIndex;
}
}
Sorted Associative Containers
Map
o A map is a sequence of (key,value) pairs where a single value is associated with
each unique key
o Retrieval of values is based on the key and is very fast.
o A map is commonly called as an associative array.
o The key is specified using the subscript operator[ ].

Prepared by A.V. KALPANA, Asst. ProfessorPage 73

CS6456 OBJECT ORIENTED PROGRAMMING

Fig. Key-value pairs in a map


#include<map>
#include<string>
#include<iostream>
class Student
{
string name;
public:
Student(){}
Student(string tname)
{
name=tname;
}
friend ostream &operator <<(ostream &tempout, Student tstudent)
{
return tempout<<tstudent.name<<\n;
}
bool operator <(Student tstudent) const
{
return(name<tstudent.name);
}
};
void main()
map<Student, int> m1;

OUTPUT:

Student s1(Mohit);

Lohit

Prepared by A.V. KALPANA, Asst. ProfessorPage 74

Mohit 1
Rohit

CS6456 OBJECT ORIENTED PROGRAMMING


Student s2(Rohit);
Student s3(Lohit);
m1[s1]=1;
m1[s2]=2;
m1[s3]=1;
m1[s4]=1;
map<Student, int>::iterator StudentIndex;
for(StudentIndex=m1.begin(); StudentIndex!=m1.end();StudentIndex++)
{
cout<<StudentIndex->first<<\t;
cout<<StudentIndex->second<<endl;
}
}
Multimap

Multimap is a container which can have entry with multiple values for a single key.
The insert function expects a pair of objects to be inserted. Pair is a template

class provided by STL.


The first element in the pair is known as first and the second element in the pair is

known as second.
Every element, when inserted, is inserted where it is to be inserted in the sorted
order.

#include<map>
#include<string>
#include<iostream>
class Student
{
string name;
public:
Student(){}
Student(string tname)
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 75

CS6456 OBJECT ORIENTED PROGRAMMING


name=tname;
}
friend ostream &operator <<(ostream &tempout, Student tstudent)
{
return tempout<<tstudent.name<<\n;
}
bool operator <(Student tstudent) const
{
return(name<tstudent.name);
}
};
void main()
{
Multimap<Student,int> m1;
Student s1(Mohit);
Student s2(Lohit);

OUTPUT:
Lohit

Mohit 1
Rohit

Student s3(Rohit);
m1.insert(pair<Student,int>(s1,1));
m1.insert(pair<Student,int>(s2,2));
m1.insert(pair<Student,int>(s3,3));
for(StudentIndex=m1.begin(); StudentIndex!=m1.end();StudentIndex++)
{
cout<<StudentIndex->first<<\t;
cout<<StudentIndex->second<<endl;
}
}
Set

A set is a collection of keys in sorted form


When we are interested only in verifying if a key is valid we can use sets.

Prepared by A.V. KALPANA, Asst. ProfessorPage 76

CS6456 OBJECT ORIENTED PROGRAMMING

We can insert all keys and when the key is referenced we can see if the key

belongs to an inserted data or not.


A set stores only a single copy.
The function insert() is used to add items to the set.
In the following example, we have inserted data of about three students thrice.
But only a single copy is stored in the set.

#include<set>
#include<string>
#include<iostream>
class Student
{
int rollno;
string name;
public:
Student(){}
Student(int trollno, string tname)
{
rollno=trollno;
name=tname;
}
friend ostream &operator <<(ostream &tempout, Student tstudent)
{
return tempout<<tstudent.rollno<<\t<<tstudent.name<<\n;
}
bool operator <(Student tstudent) const
{
return(rollno<tstudent.rollno);
}
};
void main()
{
Prepared by A.V. KALPANA, Asst. ProfessorPage 77

OUTPUT:
1234

Mohit

1235

Lohit

1236

Rohit

CS6456 OBJECT ORIENTED PROGRAMMING


Set<Student> ss;
Student s1(1234, Mohit);
Student s2(1235,Lohit);
Student s3(1236,Rohit);
ss.insert(s1);
ss.insert(s2);
ss.insert(s3);
ss.insert(s1); //inserting the same data second time
ss.insert(s2);
ss.insert(s3);
ss.insert(s1); //inserting the same data third time
ss.insert(s2);
ss.insert(s3);
Set<Student>::iterator Studentindex;
for(Studentindex=ss.begin(); Studentindex!=ss.end(); Studentindex++)
{
cout<<*StudentIndex;
}
}
Multiset
The set can have only a single copy of a key.
If more than one copy of a key is required, we can use multiset.
#include<set>
#include<vector>
#include<string>
#include<iostream>
class Student
{
int rollno;
string name;
public:
Prepared by A.V. KALPANA, Asst. ProfessorPage 78

CS6456 OBJECT ORIENTED PROGRAMMING


Student(){}
Student(int trollno, string tname)
{
rollno=trollno;
name=tname;
}
friend ostream &operator<<(ostream &tempout, Student tstudent)
{
return tempout<<tstudent.rollno<<\t<<tstudent.name<<\n;
}
bool operator <(Student tstudent) const
{
return(rollno<tstudent.rollno);
}
};
void main()

OUTPUT:
1234

Mohit

multiset<Student> mss;

1234

Mohit

Student s1(1234, Mohit);

1235

Lohit

Student s2(1235,Lohit);

1235

Lohit

Student s3(1236,Rohit);

1236

Rohit

1236

Rohit

mss.insert(s1);
mss.insert(s2);
mss.insert(s3);
mss.insert(s1); //inserting the same data second time
mss.insert(s2);
mss.insert(s3);
Set<Student>::iterator Studentindex;

for(Studentindex=mss.begin(); Studentindex!=mss.end(); Studentindex++)


{
cout<<*StudentIndex;
Prepared by A.V. KALPANA, Asst. ProfessorPage 79

CS6456 OBJECT ORIENTED PROGRAMMING


}
}
Stack

Stack follows LIFO(Last In First Out) principle.


In stack, the first inserted item inserted will be removed from the stack.
In otherwords, the last item inserted into the stack will be removed from the

stack.
empty() - used to check whether the stack has any item or not.
top() - to move the stack pointer to the top of the stack.

#include<stack>
#include<string>
#include<iostream>
class Student
{
int rollno;
string name;
public:
Student(){}
Student(int trollno, string tname)
{
rollno=trollno;
name=tname;
}
friend ostream &operator(ostream &tempout, Student tstudent)
{
return tempout<<tstudent.rollno<<\t<<tstudent.name<<\n;
}
};
void main()
{
Stack<Student> ss;
Student s1(1234, Mohit);
Prepared by A.V. KALPANA, Asst. ProfessorPage 80

OUTPUT:
1236

Rohit

1235

Lohit

1234

Mohit

CS6456 OBJECT ORIENTED PROGRAMMING


Student s2(1235,Lohit);
Student s3(1236,Rohit);
ss.pus(s1);
ss.push(s2);
ss.push(s3);
Student st;
while(!ss.empty())
{
st=ss.top();
cout<<st.name<<\t<<st.rollno<<endl;
ss.pop();
}
}
Queue
#include<queue>
#include<string>
#include<iostream>
class Student
{
int rollno;
string name;
public:
Student(){}
Student(int trollno, string tname)
{
rollno=trollno;
name=tname;
}
friend ostream &operator(ostream &tempout, Student tstudent)
{
return tempout<<tstudent.rollno<<\t<<tstudent.name<<\n;
Prepared by A.V. KALPANA, Asst. ProfessorPage 81

CS6456 OBJECT ORIENTED PROGRAMMING


}
};
void main()

OUTPUT:

1234

Mohit

Queue<Student> qs;

1235

Lohit

Student s1(1234, Mohit);

1236

Rohit

Student s2(1235,Lohit);
Student s3(1236,Rohit);
qs.pus(s1);
qs.push(s2);
qs.push(s3);
Student st;
while(!qs.empty())
{
st=qs.front(); // this is the one difference from stack & queue
cout<<st.name<<\t<<st.rollno<<endl;
qs.pop();
}
}
ITERATORS
o Iterators are like pointers and can be used to traverse and list out container
contents.
o They are often used to traverse from one element to another, a process known as
iterating through the container.
There are two model to manage multiple objects. These methods are
o Address mechanism : The pointers to array element represent a model of address
mechanism
o Functional mechanism : The file access using get() and put() use a functional
mechanism

Prepared by A.V. KALPANA, Asst. ProfessorPage 82

CS6456 OBJECT ORIENTED PROGRAMMING


The functional approach is simpler but it has less control on the process by having the
pointer whereas the address mechanism has complete control on the process by having
the pointer.

Fig. Functionality venn diagram of iterators


o Each type of iterator is used input and output iterators for performing certain
functions.
o The input and output iterators support the least functions. They can be used to
traverse in a container.
o The forward iterator supports all operations of input and output iterators and
also retains its position in the container.
o A bidirectional iterator, while supporting all forward iterator operations,
provides the ability to move in the backward direction in the container.
o A random access iterator, combines the functionality of a bidirectional iterator
with an ability to jump to an arbitrary location.

The efficiency of the STL iterators depends on two principles:


Open design having iterators open for programmers to manipulate
Address manipulation by which the job is possible to be done in minimum steps

Prepared by A.V. KALPANA, Asst. ProfessorPage 83

S-ar putea să vă placă și