Você está na página 1de 476

1

Subject Name: Object Oriented Programming

Subject Code: 600206

Staff In-Charge : P.NITHYANANDAM. Asst.Professor

I cannot teach anybody anything; I can only make them think.

- Socrates

(PN) (MCA)(2010-11/ EVEN) (2010-13)


2
MC9222 OBJECT ORIENTED PROGRAMMING LTPC
3003
UNIT I FUNDAMENTALS 9
Object–Oriented Programming concepts – Encapsulation – Programming Elements – Program Structure –
Enumeration Types –– Functions and Pointers – Function Invocation – Overloading Functions – Scope and
Storage Class – Pointer Types – Arrays and Pointers – Call–by–Reference – Assertions – STL
UNIT II IMPLEMENTING ADTS AND ENCAPSULATION 9
Aggregate Type struct – Structure Pointer Operators – Unions – Bit Fields – Data Handling and Member
Functions – Classes – Constructors and Destructors – Static Member – this Pointer – reference semantics –
implementation of simple ADTs
UNIT III POLYMORPHISM 9
ADT Conversions – Overloading – Overloading Operators – Unary Operator Overloading – Binary Operator
Overloading – Function Selection – Pointer Operators – Visitation – Iterators – containers – List – List
Iterators
UNIT IV TEMPLATES 9
Template Class – Function Templates – Class Templates – Parameterizing – STL – Algorithms – Function
Adaptors
UNIT V INHERITANCE 9
Derived Class – Typing Conversions and Visibility – Code Reuse – Virtual Functions – Templates and
Inheritance – Run Time Type Identifications – Exceptions – Handlers – Standard Exceptions
TOTAL = 45
REFERENCES:
Ira Pohl, “Object–Oriented Programming Using C++”, Pearson Education, Second Edition, 2003.
Stanley B.Lippman, Josee Lajoie, “C++ Primer”, Pearson Education, Third Edition, 2004.
Kamthane,” Object Oriented Programming with ANSI and Turbo C++”, Person Education, 2002.
Bhave , “ Object Oriented Programming With C++”, Pearson Education , 2004.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Object-Oriented Programming

Courtesy: Mastering C++ K R Venugopal, Rajkumar, T Ravishankar


The complete Reference C++ Herbert Schildt
Waite Groups OOP in Turbo C++ Robert Lafore
4

Object Oriented Paradigm

 Object oriented programming popularly called OOPs is one of


the buzzwords in the software industry

 Structured programming and object oriented programming are


equally popular today although structured programming has a
longer history

 Structured programming and object oriented programming


fundamentally differ in the following way

Structured programming views the two core elements of


any program – data and functions as two separate entities,
OOP views them as a single entity

(PN) (MCA)(2010-11/ EVEN) (2010-13)


5

Why New Programming Paradigms?

 With the continuous decline of hardware cost, high speed


computing systems are becoming economically feasible

 Innovations in the field of computer architecture supporting


complex instructions is in turn leading to the development of
better programming environments, which suit the hardware
architecture

 More powerful tools, operating system and programming


languages are evolving to keep up with the pace of hardware
development

(PN) (MCA)(2010-11/ EVEN) (2010-13)


6

 Software for different applications need to be developed


under these environments, which is a complex process

 As a result, the relative cost of software is increasing


substantially as equal as hardware

(PN) (MCA)(2010-11/ EVEN) (2010-13)


7

OOPs ! a New Paradigm

 Object – Oriented Programming is a new way of solving


problems with computers; instead of trying to mould the
problem into something familiar to the computer, the
computer is adapted to the problem

 Object – Oriented Programming is designed around the data


being operated upon as opposed to the operations themselves

 Instead of making certain types of data fit to specific and rigid


computer operations, these operations are designed to fit to
the data

(PN) (MCA)(2010-11/ EVEN) (2010-13)


8

 OOP languages provide the ability to create class hierarchies,


instantiate co-operative objects collectively working on a
problem to produce the solution and send messages between
objects to process themselves

 The power of oop languages is that the programmer can create


modular, reusable code and as a result, formulate a program
by composition and modification of the existing modules

 Flexibility is gained by being able to change or replace modules


without disturbing the other parts of the code.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


9

 Software development speed is improved , on one hand, by


reusing and enhancing the existing code and, on the other
hand, by having programming objects that are close in
representation to the real-world objects, thus reducing the
translation burden (from a real-world representation to the
computer-world representation) for the programmer

(PN) (MCA)(2010-11/ EVEN) (2010-13)


10

Encapsulation

Data Abstraction

Single Inheritance
Comprises Supported By

Polymorphism

OOP C++
Paradig Persistence
m

Delegation

Genericity

Multiple Inheritance

(PN) (MCA)(2010-11/ EVEN) (2010-13)


11

Fundamental features of OOP

 Encapsulation
 Data abstraction
 Inheritance
 Polymorphism
 Message passing
 Extensibility
 Persistence
 Delegation
 Genericity
 Multiple Inheritance

(PN) (MCA)(2010-11/ EVEN) (2010-13)


12

Encapsulation: It is a mechanism that associate the code and


the data it manipulates into a single unit and keeps them safe
from external interference and misuse. In C++, this is
supported by a construct called class.

Data abstraction: The technique of creating new data types that


are well suited to an application to be programmed is known as
data abstraction. It provides the ability to create user-defined
data types, for modelling a real world object. The class is a
construct in C++ for creating user-defined data type called
abstract data type (ADTs).

(PN) (MCA)(2010-11/ EVEN) (2010-13)


13

Inheritance: It allows the extension and reuse of existing


code without having to rewrite the code from scratch.
Inheritance involves creation of new classes (derived classes)
from the existing ones (base classes), thus enabling the
creation of a hierarchy of classes that simulate the class and
subclass concept of the real world.

Multiple Inheritance: The mechanism by which a class is derived


form more than one base class is known as multiple inheritance.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


14

Polymorphism: It allows a single name/operator to be


associated with different operations depending on the type of
data passed to it. In C++, it is achieved by function overloading,
operator overloading, and dynamic binding (virtual function).

Message Passing: It is the process of invoking an operation on an


object. In response to a message the corresponding method
(function) is exectuted in the object. It is supported in C++.

Extensibility: It is a feature, which allows the extension of the


functionality of the existing software components. It is supported
by abstract class and inheritance in C++.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


15

Persistence: The phenomenon where the object (data) outlives


the program execution and exists between executions of a
program is known as persistence. All database systems support
persistence. In C++, this is not supported . However, the user
can build it explicitly using file streams in program.

Delegation: It is an alternative to class inheritance. Delegation


is a way of making object composition as powerful as
inheritance. In C++, delegation is realized by using object
composition. This approach takes a view that an object can be a
collection of many objects and the relationships is called has-a
relationship or containership.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


16

Inheritance

Class Foundation { F W R
}
Class Wall {
H
}
Class Room {
}
Class House {
}

Class House: public Foundation,Walls,Room {


}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


17

Inheritance

F
Class Foundation {
}
W
Class Wall : public Foundation {
} R
Class Room: public Wall {
}
H
Class House: public Room {
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


18

Delegation-Object Composition ( Has-a-Relationship)

Class Foundation {
}
Class Wall {
}
Class Room {
}

Class House {
Foundation F;
Wall W;
Room R;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


19

Genericity: It is a technique for defining software components


that have more than one interpretation depending on the data
type or parameters. Thus , it allows the declaration of data
items without specifying their exact data type. Such unknown
data types (generic data type) are resolved at the time of their
usage (function call) based on the data type of parameters. In
C++, genericity is realized through function template and class
template.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


20

Moving from C to C++

 Single line comment //

 Scope Resolution Operator ::

int num =20;


void main()
{
int num =10;
cout<<“local=“<<num;
cout<<“gloabal=“<<::num;
cout<<“global + local”<<::num+num;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


21

 Variable definition at the point of use

 Variable Aliases – Reference variables

C++ supports one more type of variable called reference


variable, in addition to the value variable and pointer
variable.

Datatype & Reference variable = value variable

int &a=b; // a is an alias of int b

(PN) (MCA)(2010-11/ EVEN) (2010-13)


22

1. char &ch1=ch;
2. int &a=b;
3. float &x=y;
4. double &height = length;
5. int &x=y[100]; // x is an alias of y[100]th element
6. int n;
int *p=&n;
int &m=*p; // these declaration cause m to refer n

(PN) (MCA)(2010-11/ EVEN) (2010-13)


23

void main()
{
int a =1,b=2,c=3;
int &z=a;
cout<<“a=“<<a<<“b=“<<b<<“c=“<<c<<“z=“<<z<<”\n”;
z=b;
cout<<“a=“<<a<<“b=“<<b<<“c=“<<c<<“z=“<<z<<”\n”;
z=c;
cout<<“a=“<<a<<“b=“<<b<<“c=“<<c<<“z=“<<z<<”\n”;
cout<<“&a=“<<&a<<“&b=“<<&b<<“&c=“<<&c<<“&z=“<<&z;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


24

a=1 b=2 c =3 z=1


a=2 b=2 c =3 z=2
a=3 b=2 c =3 z=3
&a=0xff4 &b=0xff2 &c=0xff0 &z=0xff4

In main(), the statements


z=b;
z=c;
assign the value of variables b and c to the variable a since, the
reference variable z is its alias variable. It can be observed that,
in the last line of above program output, the memory address of
the variable a and z are same. The reference variables are
bound to memory locations at compile time only.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


25

Consider the following statements


int n;
int *p=&n;
int &m=*p;

Here m refers to n, which is pointed to by the variable p. The


compiler actually binds the variable m to n but not to the pointer.
If pointer p is bound to some other variable at runtime , it does
not affect the value referenced by m and n.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


26

void main()
{
int n=100;
int *p=&n;
int &m=*p;
cout<<“n =“<<n<<“m=“<<m<<“*p=“<<*p<<endl;
int k=5;
p=&k;
k=200;
cout<<“n =“<<n<<“m=“<<m<<“*p=“<<*p<<endl;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


27

n=100 m = 100 *p = 100


n=100 m = 100 *p = 200

In main(), the statement

P=&k; // pointer value changed

Changes the pointer value of p, but does not affect the


reference variable m and the variable n.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


28

 Strict Type Checking


C++ is a strongly- typed language and it uses very strict type
checking. A prototype must be known for each function which is
called, and the call must match the prototype. In C++, function
prototype is compulsory if the definition is not placed before the
function call whereas, in C , it is optional.

 Default Arguments
In a C++ function call , when one or more function arguments
are omitted, the function may be defined to take default values
for omitted arguments by providing the default values in the
function prototype.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


29

void Printline(char = ‘-’, int = 40, int =1);


void main() {
Printline(); // uses all default argumets
Printline(‘!’); // assumes 2nd and 3rd argument as default
Printline(‘*’,10); // assume 3rd argument as default
Printline(‘$’,30,2);// ignore default arguments }
void Printline(char ch,int times, int nlines) {
int i,j;
for(i=0;i<nlines;i++) cout<<endl;
for(j=0;j<times;j++) cout<<ch; }
----------------------------------------
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
**********
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

(PN) (MCA)(2010-11/ EVEN) (2010-13)


30
How to construct C++ Program (moving from C to C++)

#include<stdio.h>
void showdata(struct stud *t) {
#include<conio.h>
cout<<" mark1 mark2 mark3\n";
#include<iostream.h>
struct stud cout<<t->mark1<<t->mark2<<t->mark3;
{ }
int mark1, mark2,int mark3,total; void processdata(struct stud *t) {
};// end of structure t->total=t->mark1+t->mark2+t->mark3;
void getdata(struct stud *t) { }
cout<<"enter mark1";
void main() {
cin>>t->mark1;
struct stud st1;
cout<<"enter mark2";
cin>>t->mark2; getdata(&st1);
cout<<"enter mark3"; showdata(&st1);
cin>>t->mark3; processdata(&st1);
t->total=0; cout<<"total = "<<st1.total;
} }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


31
C++ Structure

void showdata() {
cout<<" mark1 mark2 mark3\n";
#include<stdio.h> cout<<mark1<<mark2<<mark3;}
#include<conio.h> void processdata()
{
#include<iostream.h>
total=mark1+mark2+mark3;
struct stud { }
int mark1,mark2,mark3,total; };// end of structure
void getdata() { void main() {
struct stud st1;
cout<<"enter mark1";
st1.getdata();
cin>>mark1; st1.showdata();
cout<<"enter mark2"; st1.processdata();
cin>>mark2; cout<<"total = "<<st1.total;
}
cout<<"enter mark3";
cin>>mark3;
total=0;
}
(PN) (MCA)(2010-11/ EVEN) (2010-13)
C++ Class 32
#include<stdio.h> void showdata() {
#include<conio.h> cout<<" mark1 mark2 mark3\n";
cout<<mark1<<mark2<<mark3;}
#include<iostream.h>
void processdata()
class stud {
{
public:
total=mark1+mark2+mark3;
int mark1,mark2,mark3,total; }
void getdata() { };// end of class
cout<<"enter mark1";cin>>mark1; void main() {
cout<<"enter mark2";cin>>mark2; struct stud st1; st1.getdata();
cout<<"enter mark3";cin>>mark3; st1.showdata(); st1.processdata();
total=0; cout<<"total = "<<st1.total;
} }

Note: C++ structure and class are similar in functionalities and


operation; except the member component visibility. In C++
structure the member component is public by default whereas
it is private by default in class
(PN) (MCA)(2010-11/ EVEN) (2010-13)
33

C++ Program Structure

Include files

Class declaration

Member functions declaration

Main function program

(PN) (MCA)(2010-11/ EVEN) (2010-13)


34

Program Elements

 Comments
 Keywords
 Identifiers
 Literals
 Operators and Punctuators
 Input/Output

int a,b;
cout<<“enter the input for a and b”;
cin>>a>>b;
cout<<“sum of a and b is “<<a+b;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


35

Function Overloading – Compile time Polymorphism

 Function overloading or function polymorphism is a concept


that allows multiple functions to share the same name varying
in signature

 Function polymorphism implies that the function definition can


have multiple forms

 Assigning one or more function body to the same name is


known as function overloading or function name overloading

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Multiple functions for swapping element of 36

different data types but with different function


name

void swap_char(char &x, char &y){


char t; t=x; x=y; y=t; } void main() {
char ch1,ch2; float f1,f2; int i1,i2;
void swap_int(int &x, int &y){ ch1=‘a’; ch2=‘b’; f1=3.5; f2=4.6;
int t; t=x; x=y; y=t; } i1=56; i2=89;
swap_char(ch1,ch2);
void swap_float(float &x,float &y){ cout<<ch1<<ch2<<endl;
float t; t=x; x=y; y=t; } swap_int(i1,i2);
cout<<i1<<i2<<endl;
swap_float(f1,f2);
cout<<f1<<f2<<endl;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


37

The program shown below performing the same


operation as in the earlier program, but differ in
sharing the same function name.

void main() {
void swap(char &x, char &y){ char ch1,ch2; float f1,f2; int i1,i2;
char t; t=x; x=y; y=t; } ch1=‘a’; ch2=‘b’; f1=3.5; f2=4.6;
i1=56; i2=89;
void swap(int &x, int &y){ swap(ch1,ch2);
int t; t=x; x=y; y=t; } cout<<ch1<<ch2<<endl;
swap(i1,i2);
void swap(float &x, float &y){ cout<<i1<<i2<<endl;
float t; t=x; x=y; y=t; } swap(f1,f2);
cout<<f1<<f2<<endl;
}
Go back

(PN) (MCA)(2010-11/ EVEN) (2010-13)


38

 In C++, one or more functions can be given the same name


provided the signature (parameters count or their data types) of each
of them is unique either in the number or data type of their
arguments.

 The compiler will not consider return type in discriminating one with
the other in function overloading.

int add (int, int);


float add (int, int);

int i;
i=add(5,6);
cout<<add(5,6);

(PN) (MCA)(2010-11/ EVEN) (2010-13)


39
Assertion and Program Correctness

 Assertions are program check for correctness that, if


violated, force an error exit

 Program correctness can be viewed in part as a proof that


the computation terminated with correct output depends
on correct input

 In computer programming, an assertion is a predicate(for


example a true–false statement) placed in a program to
indicate that the developer thinks that the predicate is
always true at that place

(PN) (MCA)(2010-11/ EVEN) (2010-13)


40
The following code, contain two assertions

x := 5;
{x > 0} Assertion
x := x + 1
{x > 1} Assertion

 Programmers can use assertions to help specify programs and to


reason about program correctness

 For example, a precondition — an assertion placed at the beginning


of a section of code — determines the set of states under which the
programmer expects the code to execute

 A postcondition — placed at the end — describes the expected state


at the end of execution

(PN) (MCA)(2010-11/ EVEN) (2010-13)


41

Classes and Objects

Data

data1
data2
data3

Functions
func1 ( )
func2 ( )
func3 ( )

Class Grouping Data and Functions

(PN) (MCA)(2010-11/ EVEN) (2010-13)


42

Class Specification

class className {

// body of the class

};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


43
Example

Student Class Car Class

int wheel

int roll_no int door

char color [10]


char name[20]
move ( )
setdata ( )
stop ( )

showdata ( ) reverse ( )

(PN) (MCA)(2010-11/ EVEN) (2010-13)


44

class student {
private:
int roll_no; char name[20];
public:
void setdata (int roll_no_in, char *name_in)
{
roll_no=roll_no_in; strcpy(name,name_in);
}
void outdata()
{
cout<<“Rollno=“<<roll_no<<endl;
cout<<“Name=“<<name<<endl;
}
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


45

Class Objects

class ClassName ObjectName, …;

class student s1;


or
student s1;

student s1,s2,s3,s4;

student s[4];

(PN) (MCA)(2010-11/ EVEN) (2010-13)


46

Accessing Class Members

Syntax for accessing data member


Name of the user defined object

member access specifier

data member of a class


ObjectName . DataMember

(PN) (MCA)(2010-11/ EVEN) (2010-13)


47

Syntax for accessing member function of a class


Name of the user defined object
member access specifier1
data member of a class
arguments to the function

ObjectName . FunctionName (Actual Arguments)

(PN) (MCA)(2010-11/ EVEN) (2010-13)


48

Defining Member Function

 Inside the class specification

 Outside the class speciation

 Scope resolution operator ::

user defined class name


scope resolution operator
ReturnType ClassName:: MemberFunction (arguments)

(PN) (MCA)(2010-11/ EVEN) (2010-13)


49

Example

class student {
int roll_no; char name[20];
public:
void main()
void setdata (int roll_no_in, char
*name_in) {
{ roll_no=roll_no_in; student s1,s2;
strcpy(name,name_in); } s1.setdata(10,”raja”);
void outdata(); s2.setdata(20,”ramu”);
}; s2.outdata();
void student::outdata() s2.outdata();
{ }
cout<<“Rollno=“<<roll_no<<endl;
cout<<“Name=“<<name<<endl;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


50

Accessing member function with in the class

A member function of a class can call any other member function


call of its own class irrespective of its privilege and this situation
is called nesting of member funct ion.
class NumberPairs { void main() {
int num1,num2; NumberPairs n1;
public: n1.read();
void read() { n1.ShowMax();
cout<<“enter 1st & 2nd no.”; }
cin>>num1>>num2; }
int max() {
return num1>num2?num1:num2;}
void ShowMax()
{ cout<<“maximum =“<<max(); }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Inline Function 51

 Function execution involves the overhead of jumping to and from


the calling statement
 Trading of this overhead in execution time in considerably large
whenever a function is small, and hence in such cases, inline
functions can be used
 A function in C++ is treated as macro if the keyword inline
precede its definition

 Like register specifier,inline is just actually a request,not a command,


to the compiler;the compiler reserves the right to ignore it or accept it
 Generally to qualify a function as inline, the function definition should
be very small, non recursive,non iterative and non I/O statements

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Example 52

#include <iostream.h> #include <iostream.h>


inline int max(int a, int b) void main()
{ {
return a>b ? a : b; cout << (10>20 ? 10 : 20);
} cout << " " << (99>88 ? 99 : 88);
}
void main()
{
cout << max(10, 20);
cout << " " << max(99, 88);
}

The Significant feature of inline function is that there is no explicit


function call; the function body is substituted at the point of inline
function call. Thereby, the runtime overhead for function linkage
mechanism is reduced.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


53

Data Hiding Back

Access control specifier


class classname {
private: //optional
………. //visible to member function within its class
………
protected: // visible to member function of its own class
………. // and derived class member function too
………
public: // Visible through member function, derived class
………. // and through object
………
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


54

Private Members

class person {
private:
……..
……..
int age; // private data
int getage(); // private function
};

person p1;
int a=p1.age; // cannot access private data
int age=p1.getage(); // cannot access private function

(PN) (MCA)(2010-11/ EVEN) (2010-13)


55

Protected Members

class person {
protected:
……..
……..
int age; // protected data
int getage(); // protected function
};

person p1;
int a=p1.age; // cannot access protected member
int age=p1.getage(); // same as private

(PN) (MCA)(2010-11/ EVEN) (2010-13)


56

Public Members

class person {
public:
……..
……..
int age; // public data
int getage; // public function
};

person p1;
int a=p1.age; // can access public data
int age=p1.getage(); // can access public function

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Access Boundary of Object Revisited

Access Accessible to
Specifier
Own Class Object of a
members Class

Public: Yes Yes

Private: Yes No

Protected: Yes No
58

The following declaration of a class illustrates the visibility limit


of the various class members:
class MyClass {
private:
int a;
void f1() {
//can refer to data members a,b,c and function f1,f2 and f3 }
protected:
int b;
void f2() {
//can refer to data members a,b,c and function f1,f2 and f3 }
public:
int c;
void f3() {
//can refer to data members a,b,c and function f1,f2 and f3 }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


59

Consider the statements


MyClass objx;
int d;
 Accessing private members of the class MyClass
d=objx.a; // Error: Myclass::’a’ is not accessible
objx.f1(); // Error: Myclass::’f1()’ is not accessible
 Accessing protected members of the class MyClass
d=objx.b; // Error: Myclass::’b’ is not accessible
objx.f2(); // Error: Myclass::’f2()’ is not accessible
 Accessing public members of the class MyClass
d=objx.c; // OK
objx.f3(); // OK

(PN) (MCA)(2010-11/ EVEN) (2010-13)


60

Empty Classes

Class xyz { };
Class empty
{
};
Significant usage of empty classes can be found in Exception
Handling.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


61

Pointers within a Class

 The size of data members such as vectors when defined using


arrays must be known at compile time itself

 In this case, vector size cannot be increased or decreased


irrespective of the requirement

 This inflexibility of arrays can be overcome by having a data


member for storing vector elements whose size can be
dynamically changed during run time

(PN) (MCA)(2010-11/ EVEN) (2010-13)


62

void Vector::show_sum(){
class Vector {
int sum=0;
int *v,sz;
for(int i =0;i<sz;i++)
public:
sum+=v[i];
void VectorSize(int size) {
cout<<“vector sum is “<<sum;}
sz=size; v=new int[size]; }
void release() {
void main() {
delete v; }
Vector v1; int count;
void read();
cout<<“enter size of vector”;
void show_sum();
cin>>count;
};
V1.VectorSize(count); V1.read();
void Vector::read() {
V1.show_sum(); V1.release();
for(int i =0;i<sz;i++)
cin>>v[i]; }
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


63

Passing Object as Arguments

It is possible to have functions which take objects of a class as


arguments , just as there are function which accept other
variables as arguments.

An object can be passed as an argument to a function by the


following way

 Pass-by-value, a copy of the object is passed to the function


 Pass-by-reference, the address of the object is passed implicitly
to the function
 Pass-by-pointer, the address of the object is passed explicitly to
the function

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Passing Object by Value 64
class distance {
float feet,inches;
public:
void init(float ft, float in) {
feet=ft; inches=in; } void main() {
void read() { distance d1,d2,d3;
cout<<“Enter feet:”; cin>>feet; d2.init(100.0,45.0);
cout<<“Enter inches:”; cin>>inches; } d1.read();
void show() { cout<<“d1=“; d1.show();
cout<<feet<<“-"<<inches<<“\””; } cout<<“\n d2=“; d2.show();
void add(distance d1,distance d2) { d3.add(d1,d2); \\d3=d1+d2
feet=d1.feet+d2.feet; cout<<“\n d3 = d1+d2 =“;
inches=d1.inches+d2.inches;
d3.show(); }
while(inches>=12.0)
Enter feet : 123.0
{
feet+=1.0; Enter Inches: 22.0
inches-=12.0; d1= 123’- 22”
}}}; d2= 100’ -45”
d3= d1+d2 = 228’-7”

(PN) (MCA)(2010-11/ EVEN) (2010-13)


d3 65

feet
feet
24.0
inches
inches
1.5

d3.add( d1, d2);

d1 d2
feet feet
d1.feet d2.feet
12.0 11.0
inches inches
d1.inches d2.inches
7.25 6.25

(PN) (MCA)(2010-11/ EVEN) (2010-13)


66
Passing object by Reference
class AccClass { void main() {
int accno, float balance; AccClass acc1,acc2,acc3;
public: float credit;
void getdata() { acc1.getdata(); acc2.setdata(10);
cin>>accno>>balance; } acc3.setdata(20,750.5);
void setdata( int accin) {
acc1.display();
accno=accin; balance=0.0; }
acc2.display(); acc3.display();
void setdata(int accin,float bal) {
cout<<“enter the amount to be
accno=accin; balance=bal; }
void display() { transferred from acc3 to acc1”;
cout<<accno<<balance; } cin>>credit;
void MoneyTransfer(AccClass & acc3.MoneyTransfer(acc1,credit);
acc, float amount) { acc1.display();
balance=balance-amount; acc2.display(); acc3.display();
acc.balance +=amount;}}; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


67
Passing object by Pointer
The members of objects passed by pointer are accessed by
using the -> operator, and they have similar effects as those
passed by reference. The earlier program require the following
changes if parameters are send by pointer.

 The prototype of the member function MoneyTransfer has to be changed to:


Void MoneyTransfer(AccClass *acc, float amount);

 The definition of the member function MoneyTransfer () has to be changed


to:
void MoneyTransfer(AccClass *acc, float amount) {
balance=balance-amount; acc->balance +=amount;}

 The statement invoking the member function MoneyTransfer () has to be


changed to acc3.MoneyTransfer(&acc1, credit);

(PN) (MCA)(2010-11/ EVEN) (2010-13)


68

Returning Objects argument

Similar to sending object as parameters to functions, it is also


possible to return objects from functions. The syntax is similar
to that of returning variables from functions. The return type of
the function is declared as the return object type.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


69
Returning Object by Value goback
void main() {
class distance { distance d1,d2,d3;
float feet,inches;
d2.init(11.0,6.25); d1.read();
public:
cout<<“d1=“; d1.show();
void init(float ft, float in) {
cout<<“\n d2=“; d2.show();
feet=ft; inches=in; }
d3=d1.add(d2); \\d3=d1+d2
void read() {
cout<<“\n d3 = d1+d2 =“;
cout<<“Enter feet:”; cin>>feet;
cout<<“Enter inches:”; cin>>inches; }
d3.show(); }
void show() { Enter feet : 12.0
cout<<feet<<“‘-”<<inches<<‘\”’; } Enter Inches: 7.25
distance add(distance &d2) { d1= 12’ -7.25”
distance dd; dd.feet=feet+d2.feet; d2= 11’- 6.25”
dd.inches=inches+d2.inches; d3= d1+d2 = 24’-1.5”
dd.inches>=12.0?dd.feet+=1.0,dd.inches-=12.0:dd. inches;
return dd }};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


70

Friend function and Friend classes

 The concept of encapsulation and data hiding dictates that


non-member functions should not be allowed to access an
object’s private and protected members.

 The policy is that if you are not a member you cannot access
the member data and functions.

 Sometimes this feature leads to considerable inconvenience


in programming.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


71

 Imagine a situation when it is required, that a function need


to operate on objects of two different classes

 During such times, a non-member function outside the class


tries to access and manipulate the private and protected
members of the class

 In C++, this is achieved by using the concept of friend

(PN) (MCA)(2010-11/ EVEN) (2010-13)


72

class X class Y

private:
data or function fy1 ( )
protected:

data or function fy2 ( )

friend class y;
friend fun1( );
friend z::
fz1( );

class Z

fun1( )
fz1 ( )
friend of x

fz2 ( )

(PN) (MCA)(2010-11/ EVEN) (2010-13)


73

Properties of Friend function

 Friend function is not the member function of the class in which it is


declared as friend

 Since it is not in the scope of the class, it cannot be called using the
object of that class

 It can be invoked like a normal function without the aid of any object
and friendship is not mutual by default

 Unlike member functions, it cannot access the member names directly


and has to use an object name and dot membership operator with each
member name (e.g. Test.x)

 It can be declared either in the public or the private part of a class and
usually, it has objects as arguments

(PN) (MCA)(2010-11/ EVEN) (2010-13)


74

Application of Friend Concept

 Bridging Classes with Friend function

 Friend Classes

 Class Friend to a Specified Class member

(PN) (MCA)(2010-11/ EVEN) (2010-13)


75

Bridging Classes with Friend function

Consider a situation when a function needs to operate on objects


of one or more different classes. To handle such situation, friend
function can be made to bridge the required classes

(PN) (MCA)(2010-11/ EVEN) (2010-13)


76

Bridging Classes with Friend function

class myclass { void main() {


private: myclass m1;
int a,b; m1.setab(5,6);
friend int add(myclass &m) cout<<"sum is=“<<add(m1);
public:
// friend function is invoked
void setab(int k1,int k2){ without object
a=k1;b=k2; } }
};
int add(myclass &m) {
return m.a+m.b; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


77

class two; int add_both(one &a, two &b){


class one {
int data1; return a.data1+b.data2; }
public:
void setdata(int init) {data1=init;}
friend int add_both(one &a, two &b); void main() {
};
class two { one a; two b;
int data2;
a.setdata (5);
public:
void setdata(int init) { b.setdata(10);
data2=init; }
friend int add_both(one &a, two &b); cout<<“sum of one and two
}; is :”<<add_both(a,b); }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


78

Friend Classes

Friend function permit an exception to the rules of data


encapsulation. The friend keyword allows a function, or all the
functions of another class to manipulate the private members
of the original class.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


79

Friend Classes
class Twovalue {
void main() {
int a; int b;
public : Twovalue ob;
void setvalue( int i, int j) { ob.setvalue(10,20);
a=i; b=j; } Min m;
int showa( ) { return a; } cout<<"Minimum
int showb( ) { return b; } of"<<ob.showa()<<"and"
friend class Min; <<ob.showb()<<"is“
}; <<m.minimum(ob);
class Min {
}
public:
int minimum(Twovalue &x) {
return x.a < x.b ? x.a : x.b; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


80
int two::findmin(one &a)
class one;
class two
{return data1<a.data2?data1:a.data2;}
{
int data1; void main() {
public: one a1; two b2;
void setdata(int d1) { data1=d1; }
a1.setdata(30);
int findmin(one&);
b2.setdata(40);
friend class one; };
class one { cout<<b2.findmin(a1);
int data2; cout<<a1.findmax(b2);
public: }
void setdata(int d2) {data2=d2; }
int findmax(two &b) {
return b.data1>data2?b.data1:data2;
}friend class two;};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


81

Class Friend to a Specified Class Member

When only specific member function of one class should


be friend function of another class; it must be specified
explicitly using the scope resolution operator :: .

(PN) (MCA)(2010-11/ EVEN) (2010-13)


82
class boy;
int girl::girlfunc(boy &b1) {
class girl
{ return b1.income1 + b1.income2; }
int income;
public:
void main() {
int girlfunc(boy &b1);
void setdata(int in) { income =in;}
boy b1; girl g1;
void show(){ b1.setdata(500,1000);
cout<<"girl income:"<<income;}}; g1.setdata(300);
class boy {
cout<<"boy b1 total income is
int income1,income2;
public:
:"<<g1.girlfunc(b1);
void setdata(int n1, int n2) g1.show(); }
{income1=n1;income2=n2; }
friend int girl::girlfunc(boy &b1);};
boy b1 total income is :1500
girl income: 300

(PN) (MCA)(2010-11/ EVEN) (2010-13)


83

Constant Parameters and Member Functions

 Certain member functions of a class, access the class


data members without modifying them

 It is advisable to declare such functions as const


(constant) functions

 A const member function is used to indicate that it does


not alter the data fields of the object, but only inspect
them

(PN) (MCA)(2010-11/ EVEN) (2010-13)


84

class demo {
int i;
This program will not
public:
compile because set_i() is
int get_i ( ) const {
declared as const. This
return i; } means that it is not
void set_i( int x ) const { allowed to modify the
i=x; } invoking object.
};
void main() {
demo ob;
ob.set_i(1500);
cout<<ob.get_i();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


85

Structures and Classes

 Structures and classes in C++ are given the same set of


features; For example, structures may also be used to group
data as well as functions

 In C++, the difference between structure and classes is that


by default , structure members have public accessibility,
whereas class members have private access control unless
otherwise explicitly stated

 This applies for inheritance too

(PN) (MCA)(2010-11/ EVEN) (2010-13)


86

Class, Objects and Memory Resource

 When a class is declared, memory is not allocated to the data


members of the class

 Thus, there exists a template , but data members cannot be


manipulated unless an instance of this class is created by
declaration and definition

 The organization of memory resource for the object is shown


below

(PN) (MCA)(2010-11/ EVEN) (2010-13)


87
Object 1 Object 2 Object N

data1 data1 data1

data 2 data2 data2


. . .
. . .

dataM dataM dataM

fun 1()

Separate memory for


fun 2() Shared memory for
object’s data members class functions
fun 3()
.
.

fun k()
(PN) (MCA)(2010-11/ EVEN) (2010-13)
88
Static Data members

 Whenever a class is instantiated, memory is allocated to the created


object, but there exists an exception to this rule

 Storage space for data members which are declared as static is


allocated only once during the class declaration

 Subsequently, all objects of this class have access to this data


member, i.e. all instance of the class access the same data member

 When one of them modifies the static data member, the effect is
visible to all the instance of the class

 The organization of memory resource for the object’s static data


member is show below

(PN) (MCA)(2010-11/ EVEN) (2010-13)


89
Object 1 Object 2 Object 3

data1 data1 …
data1

data 2 data2 data2


. . .
. . .

dataM dataM dataM

static data 1

Separate memory for static data 2 Shared memory for class’s


class’s automatic data static data members
members static data 3
.
.
static data k
(PN) (MCA)(2010-11/ EVEN) (2010-13)
90

Static Data and Member function

 Each object of a class has its own set of public or private data

 Each public or private function then accesses the object’s


own version of data

 There are situations, where it is desirable to have one or


more common data fields, which are accessible to all objects
of the class

 C++ therefore allows static data and functions, which are


common to all object of a class

(PN) (MCA)(2010-11/ EVEN) (2010-13)


91

Static Data Member Definition

class Classname
{
storage qualifier
………
static data member

static Datatype DataMember;


………

}; Initialization is optional

DataType Classname :: DataMember = InitialValue;

Static data member declaration in a class and its definition outside the class

(PN) (MCA)(2010-11/ EVEN) (2010-13)


92

Private Static Data Members

 When a data member want to be accessible in more than one


function, the normal procedure followed in function oriented
language is to declare it as an external variable

 But this technique may be harmful as it exposes external data


variable to accidental modification

 It may have undesirable effect on the efficient and reliable


working of the program

 C++ provides an elegant solution to that problem in the form of static


data members

 Declare the static data member in the private portion of a


class, thus achieving data hiding (encapsulation)

(PN) (MCA)(2010-11/ EVEN) (2010-13)


93

void main ( ) {
class myclass {
myclass obj1; obj1.show();
static int count;
obj1.set(100); obj1.show();
int number;
myclass obj2,obj3;
public:
obj2.set(200);obj2.show();
void set (int num)
{ number=num; ++count; } obj2.set(250); obj3.set(300);
void show() { obj1.show(); }
cout<<“\count is =:”<<count;
count is = 0
}
count is = 1
};
count is = 2
int myclass :: count=0;
count is = 4

(PN) (MCA)(2010-11/ EVEN) (2010-13)


94

class shared{ void main(){


static int a; shared x,y; x.set(1,1);
int b; x.show(); y.set(2,2);
public: y.show(); x.show();
void set (int i,int j){ }
a=i; b=j;}
void show();
Static a : 1
};
Non-static b : 1
int shared :: a;
Static a : 2
void shared :: show(){
Non-static b : 2
cout<<“static a: “<<a;
cout<<“non-static b :”<<b<<endl; Static a : 2
} Non-static b : 1

(PN) (MCA)(2010-11/ EVEN) (2010-13)


95

One use of static member variable is to provide access control to


some shared resource used by all the object of a class.

For example, you might create several objects, each of which


needs to write to file at a time.

In this case, you will want to declare a static variable that


indicates when the file is in use and when it is free.

Each object then vigilance this variable before writing to the


File.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


96

class cl { void main() {


static int resource; cl ob1, ob2;
public: if(ob1.get_resource()) cout
int get_resource(); << "ob1 has resource\n";
void free_resource() {resource = 0;} if(!ob2.get_resource()) cout
}; << "ob2 denied
int cl::resource; // define resource resource\n";
int cl::get_resource() { ob1.free_resource();
if(resource) return 0; // let someone else use it
// resource already in use if(ob2.get_resource())
else { resource = 1; return 1;
cout << "ob2 can now use
// resource allocated to this object resource\n";
}
}
}
ob1 has resource
ob2 denied resource
ob2 can now use resource

(PN) (MCA)(2010-11/ EVEN) (2010-13)


97

Access Rule for Static Data Member

 The static data members which are declared in public limit are
similar to normal global variables, they can be reached by
prefixing class name and scope resolution :: operator or
through the instance of that class

 The static data members which are declared in private limit


cannot reached by neither class name and scope resolution ::
operator nor through the instance of that class, they can be
accessed by using the public handle alone

(PN) (MCA)(2010-11/ EVEN) (2010-13)


98

class Test { void main () {


private: Test::public_int=145; //ok
static int private_int; Test::private_int=15; //wrong
public: Test obj;
static int public_int; obj.public_int=145; //ok
}; obj.private_int=15; //wrong
}
int Test::public_int;
int Test::private_int;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


99

class test {
void main(){
static int privateint;
test::publicint=100;
static void privatefunction() {
cout<<"i am static private // Wrong test::privateint=200;
function\n"; } test::publicfunction(); //ok
public: // wrong test::privatefunction();
static int publicint; test obj1;
static void publicfunction() { obj1.publicint=100;//ok
cout<<"i am static public function\n";
// wrong obj1.privateint=200;
privatefunction(); }
obj1.publicfunction();//ok
};
//wrong obj1.privatefunction();
int test::privateint;
int test::publicint; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


100

Static Member Function

 Besides static data, C++ allows the definition of static


functions

 The static functions can access only the static members


(data or function) in the same class; non-static data are
unavailable to these functions

 Static member functions declared in the public part of a


class declaration can be accessed without aid of an
object of that class

(PN) (MCA)(2010-11/ EVEN) (2010-13)


101

void main( ) {
class directory{
cout<<“path:”<<directory::path;
public:
directory::setpath(“/usr”);
static char path[ ];
directory dir;
static void setpath (char const
cout<<“path:”<<directory::path;
*newpath);
dir.setpath(“/etc”);
};
cout<<“path:”<<dir.path; }
char directory::path[100]=“/usr/raj”;
Path: /usr/raj
void directory ::setpath(char const
*newpath){ Path: /usr
strcpy(path,newpath); } Path: /etc

(PN) (MCA)(2010-11/ EVEN) (2010-13)


102

Properties of static data function

 Only one copy of static data member exists for all the
instance of a class

 Static member functions can access only static member of


its class

 Static data member must be defined and initialized like


global variables, otherwise the linker generates error

(PN) (MCA)(2010-11/ EVEN) (2010-13)


103

Object Initialization and Clean-up : Constructor

 A constructor is a special member function whose main


operation is to allocate the required resources such as
memory and initialize the objects of a class

 A constructor is also a member function has the same as its


class invoked automatically

 It can be overloaded, no return type and must be declared in


the public portion of a class

(PN) (MCA)(2010-11/ EVEN) (2010-13)


104

class classname {

…..
…..
public:
classname(){ definition inside}
…..
……
};

classname::classname() {definition outside }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


105

class Counter {
private: unsigned int count;
void main() {
public: Counter() : count(0){}
Counter c1, c2;
void inc_count() {
cout<<“\nc1=”<< c1.get_count();
count++; } cout<<“\nc2=”<<c2.get_count();
int get_count() { c1.inc_count(); //increment c1
return count; } c2.inc_count(); //increment c2
}; c2.inc_count(); //increment c2
cout <<“\nc1=”<<c1.get_count();
cout <<“\nc2=”<<c2.get_count();
}
c1=0
c2=0
c1=1
c2=2

(PN) (MCA)(2010-11/ EVEN) (2010-13)


void main() { 106
Test X;
Class Test { cout<“main function\n”;
public: func();
Test(); };
}; Constructor of class Test called
Test::Test() { (global object G)
cout<<“constructor of class Constructor of class Test called
test called \n ”; (object X in main)
} main() function
Test G; Constructor of class Test called
void func() { (object L in func())
Test L; here’s function func()
cout<<“here’s function func()\n”;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


107

back
Parameterized Constructors

class box { void main() {


double width,height,depth; box mybox1(10,20,15);
public: box mybox2(3,6,9);
//Initialisation list concept cout<<mybox1.volume();
box(double w,double h, cout<<mybox2.volume();
double d): width(w), }
height(h), depth(d){}
double volume() { 3000.0
return width*height*depth; 162.0
}
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


108

Destructor

 When an object is no longer needed it can be destroyed

 A class can have another special member function


called the destructor, which is invoked when an object
is destroyed

 A destructor is a special member function whose main


operation is to de-allocate the required resources such
as memory of a class

 A destructor is also a member function has the same as


its class invoked automatically

 It cannot be overloaded, no return type and must be


declared in the public portion of a class

(PN) (MCA)(2010-11/ EVEN) (2010-13)


109

class classname {

…..
…..
public:
~classname(){ definition inside}
…..
……
};

classname::~classname() {definition outside }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


110

void main() {
class test { test x;
public: cout<<“Terminating main()\n”;
test(); }
~test(); };
test::test() {
cout<<“constructor of test
class called\n”;
}
constructor of test class called
test::~test() {
Terminating main
cout<<“destructor of test
destructor of test class called
class called\n”;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


111
Order of Construction and Destruction
void func() {
Test L("func");
class Test {
cout<<"here is function
char *name;
func()"<<endl; }
public:
Test(char*); ~Test(); void main() {
}; Test X("main");
func();
Test::Test(char *namein) { cout<<"main function
name=new char[strlen(namein)+1]; termination"<<endl;}
strcpy(name,namein);
cout<<"Test object "<<name<<"
created"<<endl; Test object global created
} Test object main created
Test::~Test() { Test object func created
cout<<"Test object "<<name<<“ here is function func()
destroyed"<<endl; delete name; } Test object func destroyed
main function termination
Test object main destroyed
Test G("global");
Test object global destroyed

(PN) (MCA)(2010-11/ EVEN) (2010-13)


112

int nobjects=0; void main ( ) {


int nobj_alive=0; myclass obj1;
obj1.show ( );
class myclass {
{
public: myclass obj1,obj2;
myclass ( ) { obj2.show(); }
++nobjects; ++ nobj_alive; obj1.show ( );
} myclass obj2,obj3;
~myclass ( ) { obj2.show ( );}
--nobj_alive; } total object created :1
void show ( ) { currently alive :1
total object created :3
cout<< “total object created”
currently alive :3
<<nobjects<<endl; total object created :3
cout<< “currently currently alive :1
alive”<<nobj_alive<<endl;} total object created :5
}; currently alive :3

(PN) (MCA)(2010-11/ EVEN) (2010-13)


113

Static Data Members with Constructors & Destructors

class myclass { void main ( ) {


myclass obj1;
static int nobjects;
obj1.show ( );
static int nobj_alive; {
public: myclass obj1,obj2;
myclass ( ) { obj2.show(); }
++nobjects; ++ nobj_alive; obj1.show ( );
} myclass obj2,obj3;
obj2.show ( );}
~myclass ( ) {
total object created :1
--nobj_alive; } currently alive :1
void show ( ) { total object created :3
cout<< “total object created” currently alive :3
<<nobjects<<endl; total object created :3
cout<< “currently currently alive :1
alive”<<nobj_alive<<endl;} total object created :5
}; currently alive :3
int myclass::nobjects=0;
int myclass::nobj_alive=0;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


114

Constructor Overloading

 An interesting feature of constructor overloading is that a


class can have multiple constructors

 This is called constructor overloading

 All the constructors have the same name as the


corresponding class, and they differ only in terms of their
signature

(PN) (MCA)(2010-11/ EVEN) (2010-13)


115
class AccClass {
int accno, float balance; void main() {
public: AccClass acc1
AccClass() { AccClass acc2(10);
cin>>accno>>balance; }
AccClass acc3(20,750);
AccClass( int accin) { float credit;
accno=accin; balance=0.0; } acc1.display();
acc2.display(); acc3.display();
AccClass(int accin,float bal) {
cout<<“enter the amount to be
accno=accin; balance=bal; }
transferred from acc3 to acc1”;
void display() { cin>>credit;
cout<<accno<<balance; } acc3.MoneyTransfer(acc1,credit);
acc1.display();
void MoneyTransfer(AccClass & acc2.display(); acc3.display();
acc, float amount) {
balance=balance-amount;
}
acc.balance +=amount;}
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


116

Constructors with Default Arguments

class complex { void main() {


float x,y; complex c1(1.5,2.0);
public: complex c2(2.2);
complex() {x=y=0.0; } complex c3;
complex(float x1,float y1=0.0){ c3=c1.add(c2);
x=x1;y=y1;} cout<<"C1 = ";c1.show();
void show() { cout<<"C2 = ";c2.show();
cout<< x<<" + j"<< y <<endl; } cout<<"C3 = ";c3.show();
complex add(complex c2);};
}
c1=1.5+j2
complex complex::add(complex c2) {
complex temp; c2=2.2+j0
temp.x=x+c2.x; c3=3.7+j2
temp.y=y+c2.y;
return temp;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


117

Suppose the specification of the constructor complex (float,float) is


changed to complex(float x=0.0,float y=0.0) in the above program, it
cause ambiguity while using statement such as complex c3; the
confusion is whether to call the no-argument constructor,
complex::complex() or the two argument constructor
complex(float x=0.0,float y=0.0)

A constructor that has all default arguments is similar to a


default(no-argument) constructor, because it can be called without
any explicit arguments.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


118
class X {
int value; Trying to create an object of the class
public: X without any arguments, will cause
X() {value=0;} an error as two different constructors
X(int i=0) { value=i;} satisfy the requirement.
};
Hence the statement, X c; cause the
void main() { amibiguity whether to call X::X() or
X c1(4);//ok X::X(int i=0).
X c;//Error: This leads to
errors as compiler will not be
able to decide which constructor
should be called
} In this program, if the default
constructor is removed, the
program works properly

(PN) (MCA)(2010-11/ EVEN) (2010-13)


119

Constructor with Dynamic Operations

class Vector { void Vector::show_sum(){


int *v,sz; int sum=0;
public: for(int i =0;i<sz;i++)’
Vector(int size) { sum+=v[i];
sz=size; v=new int[size]; } cout<<“vector sum is “<<sum;}
~Vector() {
delete v; } void main() {
void read(); int count;
void show_sum(); cout<<“enter size of vector”;
}; cin>>count;
void Vector::read() { Vector v1(count); v1.read();
for(int i =0;i<sz;i++) v1.show_sum();
cin>>v[i]; }
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


120
Hybrid Constructor
class test void test::showdata()
{ {
int a,b,c,d;
public:
cout<<" a is "<<a<<endl;
test() {} cout<<" b is "<<b<<endl;
test(int k1,int k2,int k3,int k4) cout<<" c is "<<c<<endl;
{
a=k1;b=k2;c=k3;d=k4; cout<<" d is "<<d<<endl;
} }
test(test &t1,test &t2) void main()
{
a=t1.a;b=t1.b; {
c=t2.c;d=t2.d; test t1(1,2,3,4); test t2(5,6,7,8);
}
test(test &t2,int k1,int k2)
test t3(t1,t2); test t4(t2,0,0);
{ cout<<"t1 object"<<endl;
a=t2.a;b=t2.b; t1.showdata();
c=k1;d=k2;
} cout<<"t2 object"<<endl;
}; t2.showdata();
cout<<"t3 object"<<endl;
t3.showdata();
cout<<"t4 object"<<endl;
t4.showdata();
}
(PN) (MCA)(2010-11/ EVEN) (2010-13)
121
t1 object
a is 1
b is 2
c is 3
d is 4
t2 object
a is 5
b is 6
c is 7
d is 8
t3 object
a is 1
b is 2
c is 7
d is 8
t4 object
a is 5
b is 6
c is 0
d is 0

(PN) (MCA)(2010-11/ EVEN) (2010-13)


122

Copy Constructor (Deep copy – Shallow copy)

 Constructor cannot take object as arguments by value

 If a object to be send as argument to a constructor,


then it should be send by reference, which is called as
basically copy constructor

 What is the need for copy constructor?

(PN) (MCA)(2010-11/ EVEN) (2010-13)


123

void main() {
class test { test t1,t2;
int a,b; t1.setdata(5,6); t2.setdata(7,8);
public: cout<<"\n object t1"<<endl;
void addressanddata(); t1.addressanddata();
cout<<"\n object t2"<<endl;
void setdata(int k1,int k2) {
t2.addressanddata(); }
a=k1;b=k2; }
}; object t1
void test::addressanddata() { a is 5 its address is 0x8fc4fff2
cout<<" \n a is "<<a <<" its b is 6 its address is 0x8fc4fff4
address is "<<&a<<endl; object t2
cout<<" \n b is "<<b <<" its a is 7 its address is 0x8fc4ffee
address is "<<&b<<endl; } b is 8 its address is 0x8fc4fff0

(PN) (MCA)(2010-11/ EVEN) (2010-13)


124

Assignment

class base {
int a[5]; int sz; void base::dataandaddress(){
public: for(int i=0;i<sz;i++)
cout<<"address of a["<<i<<"]is
void readdata(int);
"<<&a[i]<<" data of a["<<i<<"]
void showaddress();
is "<<a[i];
void dataandaddress(); }
};
void base::readdata(int size){ void base::showaddress() {
sz=size; cout<<"address alloted in
for(int i=0;i<sz;i++) cin>>a[i]; memory is"<<a; }
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


125

void main() {
base b1,b2; cout<<"b1 ";
b1.showaddress();
cout<<"b2 ";
b2.showaddress();
cout<<"\n enter b1 data;
b1.readdata(5);
cout<<"\n b1 address and its
data member";
b1.dataandaddress();
b2=b1;//assignment
cout<<"\n b2 address and its
data member";
b2.dataandaddress(); }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


b1 address allotted in memory is 0x8f9dffea 126
b2 address allotted in memory is 0x8f9dffde
enter b1 data: 1 2 3 4 5
b1 address and its data member
address of a[0] is 0x8f9dffea data of a[0] is 1
address of a[1] is 0x8f9dffec data of a[1] is 2
address of a[2] is 0x8f9dffee data of a[2] is 3
address of a[3] is 0x8f9dfff0 data of a[3] is 4
address of a[4] is 0x8f9dfff2 data of a[4] is 5
b2 address and its data member
address of a[0] is 0x8f9dffde data of a[0] is 1
address of a[1] is 0x8f9dffe0 data of a[1] is 2
address of a[2] is 0x8f9dffe2 data of a[2] is 3
address of a[3] is 0x8f9dffe4 data of a[3] is 4
address of a[4] is 0x8f9dffe6 data of a[4] is 5

(PN) (MCA)(2010-11/ EVEN) (2010-13)


127

Default Copy Constructor

void base::readdata(int size) {


class base {
sz=size;
int a[5]; int sz; for(int i=0;i<sz;i++)
public: cin>>a[i]; }
void showaddress();
void base::dataandaddress() {
void readdata(int);
for(int i=0;i<sz;i++)
void dataandaddress(); cout<<"address of a["<<i<<"]is
}; "<<&a[i]<<"data of a["<<i<<"]
void base::showaddress() { is "<<a[i];
cout<<"address alloted in }
memory is"<<a; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


128

void main() {
base b1; cout<<"b1 ";
b1.showaddress();
cout<<"\n enter b1 data ";
b1.readdata(5);
cout<<"\n b1 address and its data member";
b1.dataandaddress();
base b2(b1); //copy constructor
cout<<"\n b2 ";
b2.showaddress();
cout<<"\n b2 address and its data member";
b2.dataandaddress();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


b1 address allotted in memory is0x8f9effea 129

enter b1 data: 1 2 3 4 5

b1 address and its data member

address of a[0]is 0x8f9effea data of a[0] is 1


address of a[1]is 0x8f9effec data of a[1] is 2
address of a[2]is 0x8f9effee data of a[2] is 3
address of a[3]is 0x8f9efff0 data of a[3] is 4
address of a[4]is 0x8f9efff2 data of a[4] is 5

b2 address allotted in memory is0x8f9effde

b2 address and its data member

address of a[0]is 0x8f9effde data of a[0] is 1


address of a[1]is 0x8f9effe0 data of a[1] is 2
address of a[2]is 0x8f9effe2 data of a[2] is 3
address of a[3]is 0x8f9effe4 data of a[3] is 4
address of a[4]is 0x8f9effe6 data of a[4] is 5

(PN) (MCA)(2010-11/ EVEN) (2010-13)


130

 A shallow copy of an object copies all of the member field


values individually

 This works well if the fields are values, but may not be what
you want for fields that point to dynamically allocated memory.

 The pointer will be copied, but the memory it points to will not
be copied

 The field in both the original object and the copy will then point
to the same dynamically allocated memory, which is not
usually what you want (deep copy required)

 The default copy constructor and assignment operator make


shallow copies

(PN) (MCA)(2010-11/ EVEN) (2010-13)


131

Deep Copy

 If an object has pointers to dynamically allocated memory,


and the dynamically allocated memory needs to be copied
when the original object is copied, then a deep copy is
required

 A deep copy copies all fields, and makes copies of dynamically


allocated memory pointed to by the fields

 To make a deep copy, you must write a copy constructor and


overload the assignment operator, otherwise the copy will
point to the original, may lead to disasterous consequences

 A Shallow copy create a new reference to the same object,


whereas a deep copy create a new reference to a new object

(PN) (MCA)(2010-11/ EVEN) (2010-13)


132

Calling compiler Default copy constructor

class base { base::base(const base &b) {


int *a,sz; sz=b.sz; a=new int[sz];
public: for(int i=0;i<sz;i++) a[i]=b.a[i]; }
base (int size) {
sz=size; void base::readdata() {
a = new int[sz]; for(int i=0;i<sz;i++) cin>>a[i]; }
cout<<"address alloted from heap
is "<<a<<endl; } void base::showdataandaddress(){
base(const base &b); for(int i=0;i<sz;i++)
~base() { delete a; } cout<<"address of a["<<i<<"]is
void readdata();
"<<&a[i]<<" data of a["<<i<<"]
void showdataandaddress();
is "<<a[i]; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


133

void main() {
base b1(5),base b2(5);
cout<<"\n enter b1 data ";
b1.readdata();
cout<<"\n b1 address and its data member";
b1.showdataandaddress();
b2=b1; //calling compiler default copy constructor
//base b2=b1; calling user defined copy constructor version
//base b2(b1); calling user defined copy constructor version
cout<<"\n b2 address and its data member";
b2.showdataandaddress();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


134

b1 address allotted from heap is 0x8fac0f6c


b2 address allotted from heap is 0x8fac0f7a
enter b1 data: 1 2 3 4 5
b1 address and its data member
address of a[0] is 0x8fac0f6c data of a[0] is 1
address of a[1] is 0x8fac0f6e data of a[1] is 2
address of a[2] is 0x8fac0f70 data of a[2] is 3
address of a[3] is 0x8fac0f72 data of a[3] is 4
address of a[4] is 0x8fac0f74 data of a[4] is 5
b2 address and its data member
address of a[0] is 0x8fac0f6c data of a[0] is 1
address of a[1] is 0x8fac0f6e data of a[1] is 2
address of a[2] is 0x8fac0f70 data of a[2] is 3
address of a[3] is 0x8fac0f72 data of a[3] is 4
address of a[4] is 0x8fac0f74 data of a[4] is 5

(PN) (MCA)(2010-11/ EVEN) (2010-13)


135

Calling User Defined overridden copy constructor


class base {
int *a,sz; void base::readdata() {
public: for(int i=0;i<sz;i++)
base (int size) { sz=size;
a = new int[sz]; cin>>a[i]; }
cout<<"address alloted from
heap is "<<a; } void base::showdataandaddress(){
base(const base &b);
for(int i=0;i<sz;i++)
~base() { delete a; }
void readdata(); cout<<"address of a["<<i<<"]is
void showdataandaddress(); "<<&a[i]<<" data of
}; a["<<i<<"] is "<<a[i]; }
base::base(const base &b) {
sz=b.sz; a=new int[sz];
cout<<"address alloted from
heap is "<<a;
for(int i=0;i<sz;i++) a[i]=b.a[i]; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


136

void main() {
cout<<"b1 "; base b1(5);
cout<<"\n enter b1 data ";
b1.readdata();
cout<<"\n b1 address and its data member";
b1.showdataandaddress();
cout<<"b2 ";
//base b2=b1;
base b2(b1);// calling overridden user defined copy constructor
cout<<"\n b2 address and its data member"<<endl<<endl;
b2.showdataandaddress(); }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


b1 address allotted from heap is 0x8fa90f68 137

enter b1 data: 1 2 3 4 5

b1 address and its data member

address of a[0]is 0x8fa90f68 data of a[0] is 1


address of a[1]is 0x8fa90f6a data of a[1] is 2
address of a[2]is 0x8fa90f6c data of a[2] is 3
address of a[3]is 0x8fa90f6e data of a[3] is 4
address of a[4]is 0x8fa90f70 data of a[4] is 5

b2 address and its data member

address of a[0]is 0x8fa90f76 data of a[0] is 1


address of a[1]is 0x8fa90f78 data of a[1] is 2
address of a[2]is 0x8fa90f7a data of a[2] is 3
address of a[3]is 0x8fa90f7c data of a[3] is 4
address of a[4]is 0x8fa90f7e data of a[4] is 5

(PN) (MCA)(2010-11/ EVEN) (2010-13)


138

 Finally heap memory is too costlier, in order to use it


efficiently and economically, the user has to define their
own user defined constructor, if it is required

 The compiler default constructor, does not make a


duplicate memory for dynamic object , the user have to
force it do explicitly in the user defined copy constructor
version

(PN) (MCA)(2010-11/ EVEN) (2010-13)


139

Nameless Object

 In addition to the creation of named objects, C++


supports the creation of unnamed objects too

classname (arguments);

 Passing argument to an object is optional and if no-


arguments are passed, a default constructor of the
class is invoked

 The scope of the nameless object is limited to only to


the statement in which it is created

 The nameless object feature facilitate in function


returning an object

(PN) (MCA)(2010-11/ EVEN) (2010-13)


140

void main() {
class nameless {
nameless().show();
public:
nameless n1;
nameless() { nameless n2;
cout<<“constructor”; } n2.show();
~nameless() { cout<<“program terminates”;
cout<<“destructor”; } }
void show() constructor <- nameless()
{ I am show called
cout<<“I am show called”; destructor <- nameless()
} constructor <- nameless n1()
constructor <- nameless n2()
};
I am show called
program terminates
destructor <- nameless n2()
destructor <- nameless n1()

(PN) (MCA)(2010-11/ EVEN) (2010-13)


141

class distance { inches>=12.0?feet+=1.0,inches-=12.0:inches;


private: return distance(feet,inches);
float feet,inches;
}
public:
distance (float ft, float in) {
feet=ft; inches=in; } void main() {
distance() { feet=0.0;inches=0.0;} distance d1(12.0,7.25);
void show() { distance d2(11.0,6.25);
cout<<feet<<"-"<<inches<<'\"'; } d1.show(); d2.show();
float getfeet() { return feet;} distance d3=add(d1,d2);
float getinches() { return inches;} cout<<"\n d3 = d1+d2 =";
}; d3.show();}
distance add(distance d1,distance d2) {
float feet=d1.getfeet()+d2.getfeet();
gotoslideno56
float inches=d1.getinches()+d2.getinches();

(PN) (MCA)(2010-11/ EVEN) (2010-13)


142

Nested Classes

 The power of abstraction of a class can be increased by


including other class declarations inside a class

 Nested classes could be used to hide specialized classes and


their instances within a host class

 The feature of nesting of classes is useful while implementing


powerful data structures such as linked lists and trees

(PN) (MCA)(2010-11/ EVEN) (2010-13)


143
student() { }
class student { ~student() { }
private: void read() {
int rollno,marks; //read members of student class
object including birthday
char name[25];
birthday.read();
char branch[15];
}
public:
//Other member of student class
class date {
};
int day,month,year;
void main()
public:
{
date() { }
student s1;
void read(){};
s1.birthday.year;//error
//other member function
of date class s1.date.day=2;//error
}birthday; s1.read();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


144

this pointer

class test {
void main() {
int a,b;
test t1(10,20);
public:
t1.show();
test(int a,int b) {
}
a=a; b=b;
}
void show() {
cout<<" a is "<<a<<endl;
cout<<" b is "<<b<<endl;
}
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


145

class test {
void main() {
int a,b;
test t1(10,20);
public:
t1.show();
test(int a,int b) {
}
this->a=a; this->b=b;
}
friend function and static
void show() {
component( data + function)
cout<<" a is "<<a<<endl;
cannot be invoked using this pointer
cout<<" b is "<<b<<endl;
}
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


146

Constant object and constructors

 C++ allows to define constant objects of user-defined


classes similar to constants of standard data types

 The data members of a constant object can be initialized


only by a constructor as part of object creation procedure

 Once a constant object is created, no member function of


its class can modify its data members

classname const objectname(parameter);

(PN) (MCA)(2010-11/ EVEN) (2010-13)


147

class test { void test::add(const test&ta, const test&tb)


int a,b; {this->a=ta.a+tb.a;
public: this->b=ta.b+tb.b;}
test() {}
test(int k1,int k2) {
void main() {
this->a=k1;this->b=k2;
test t1(5,6);test t2(7,8);
}
test t3; t1.showdata();
void showdata() {
cout<<"a is "<<a<<endl; t2.showdata(); t3.add(t1,t2);
cout<<"b is "<<b<<endl; t3.showdata();
} }
void add(const test&,const test&);
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


148

class test { void test::add(test &ta, test &tb) {


int a,b; this->a=ta.a+tb.a;
public: this->b=ta.b+tb.b;
test() {} //ta.a=100; //ta.b=200; }
test(int k1,int k2) {
this->a=k1;this->b=k2; } void main() {
void showdata() { test const t1(5,6);
cout<<"a is "<<a<<endl; test const t2(7,8);
cout<<"b is "<<b<<endl; } test t3;
void add(test&,test&); t1.showdata(); t2.showdata();
}; t3.add(t1,t2);t3.showdata();
t1.showdata();t2.showdata(); }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


149

Dynamic Objects

 C++ supports creation of objects with scoped lifetimes


(stack-based objects) and with arbitrary lifetimes (heap-based
objects)

 Stack-based objects are managed by the compiler implicitly,


whereas heap-based objects are managed by the programmer
explicitly

 The operators new and delete used with standard data type
variable’s management can also be used for creating or
destroying objects at run time respectively

(PN) (MCA)(2010-11/ EVEN) (2010-13)


150

Pointer to objects

 The new operator is used to create dynamic objects

 delete operator is used to release the memory allocated to the


dynamic object by the new operator

 A pointer variable can be defined to hold the address of an


object which is created statically or dynamically

 Such pointer variables can be used to access data or member


function of a class using the * or -> operators

(PN) (MCA)(2010-11/ EVEN) (2010-13)


151

Pointer to Object Definition

 A pointer can be made to point to an existing object, or to a


newly created object using the new operator

 binding the address of a statically created object


classname *ptr_to_object;
classname object;
ptr_to_object = &object;

 binding the address of a dynamically created object


classname *ptr_to_object;
ptr_to_object = new classname;
or
classname *ptr_to_object=new classname;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


152

Accessing Members of Objects

 There are two approaches for reaching the members of an


object whose address resides in a pointer

pointer_to_object->member_name
or
(*pointer_to_object).member_name

 The member to be accessed through the object pointer can be


either data or member function

(PN) (MCA)(2010-11/ EVEN) (2010-13)


153

void main() {
class test { test *ptr,t;
int a,b; ptr=&t;
public: t.setdata(1,2);
void setdata(int k1,int k2) { ptr->showdata();
a=k1;b=k2; } t.showdata();
void showdata() { (*ptr).showdata();
cout<<" a is "<<a<<endl; }
cout<<" b is "<<b<<endl;
} };

(PN) (MCA)(2010-11/ EVEN) (2010-13)


154

Creating and Deleting Dynamic Objects

 The syntax for creating a dynamic object using the new


operator is new classname;
ptr_to_object=new classname;

 Once a pointer holding the address of a dynamic object,its


member can be accessed by using -> operator

 The syntax of delete operator releasing memory allocated


to dynamic object is delete ptr_to_object;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


155

void main() {
class test { test *ptr=new test;
int a,b; ptr->setdata(1,2);
public: ptr->showdata();
test() { cout<<“constructor”;} (*ptr).showdata();
~test() { cout<<“destrcutor”;} delete ptr; }
void setdata(int k1,int k2) {
a=k1;b=k2; }
void showdata() {
cout<<" a is "<<a<<” b
is”<<b; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


156

 When the dynamic object pointed to, by the variable ptr goes
out of scope, the memory allocated to that object is not
released automatically

 It must be performed explicitly as delete ptr;

 The above statement releases the memory allocated to the


dynamically created object by the new operator

 In addition to this, it also invokes the destructor function


~test() to perform cleanup activities of resources allocated to
the object’s data members if any

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Live Objects – Objects created dynamically with their 157

data members initialized during creation


class student { student(int roll) { rollno=roll;
int rollno; char *name; name=NULL; }
public: student(int roll, char *n) {
student() { name=new char[strlen(n)+1];
char flag,str[50]; strcpy(name,n); rollno=roll;}
cout<<"object to be intialized ~student() {
(y/n): "; if(name) delete name;}
cin>>flag;
if(flag=='y' || flag=='Y') { void show() {
cout<<"enter rollno of student :"; if(rollno)
cin>>rollno; cout<<"Roll No: "<<rollno;
cout<<"enter name of student :"; else
cin>>str; cout<<"Roll No not initialised";
name=new char[strlen(str)+1]; if(name)
strcpy(name,str); } cout<<"Name: "<<name;
else {rollno=0;name=NULL;} else
} cout<<"Name not initialised"; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


158

object to be intialized (y/n): y


enter rollno of student :1
void main() {
enter name of student :siva
student *s1,*s2,*s3,*s4;
object to be intialized (y/n): n
s1=new student;
Roll No: 1 // object s1
s2=new student;
Name: siva
s3=new student(3);
Roll No not initialised // object s2
s4=new student(2,"rajesh");
Name not initialised
s1->show(); s2->show();
Roll No: 3 // object s3
s3->show();s4->show();
Name not initialised
delete s1; delete s2;
Roll No: 2 // object s4
delete s3; delete s4;
Name: rajesh
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Array of Objects 159

for(i=0;i<10;i++,count++) {
class student { cout<<"object to be initialized
int rollno; char name[20]; (y/n): ";
public: cin>>flag;
void setdata(int roll, char *n) if(flag=='y' || flag=='Y') {
{strcpy(name,n); rollno=roll;} cout<<"enter rollno of student :";
void showdata() { cin>>rollno;
cout<<"Roll No: "<<rollno; cout<<"enter name of student :";
cout<<"Name: "<<name; cin>>name;
}}; s[i].setdata(rollno,name);
}
else break;
void main() {
}
int i,rollno,count=0;
cout<<“student details:”;
student s[10];
for(i=0;i<count;i++) {
char flag, name[20];
s[i].showdata();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


160
Array of Pointers to Objects

for(i=0;i<10;i++,count++) {
class student {
cout<<"object to be initialized(y/n):";
int rollno; char name[20];
cin>>flag;
public:
if(flag=='y' || flag=='Y') {
void setdata(int roll, char *n)
cout<<"enter rollno of student :";
{
cin>>rollno;
strcpy(name,n); rollno=roll;
cout<<"enter name of student :";
}
cin>>name;
void showdata() {
S[i]=new student;// dynamic object
cout<<"Roll No: "<<rollno;
s[i]->setdata(rollno,name);
cout<<"Name: "<<name;
}
}};
else break; }
cout<<“student details:”;
void main() {
for(i=0;i<count;i++) s[i]->showdata();
int i,rollno,count=0;
for(i=0;i<count;i++) delete s[i];
student *s[10];
} // dynamic object deletion
char flag, name[20];

(PN) (MCA)(2010-11/ EVEN) (2010-13)


161
Invoking parameterized constructor on array of objects
class test
{int a,b,c;
void main() { Go back
public:
test()
test x[3];
{a=b=c=0; } cout<<"x objects "<<endl;
test(int k1) for(int i=0;i<3;i++)
{a=b=c=k1; } x[i].showdata();
test(int k1,int k2)
test y[3]={test(1,2),test(3,4),test(5,6)};
{a=k1;b=k2;c=0; }
test(int k1,int k2,int k3)
cout<<"y objects "<<endl;
{ a=k1;b=k2;c=k3; } for(i=0;i<3;i++)
void showdata() y[i].showdata();
{cout<<"a is"<<a; test z[4]
cout<<"b is "<<b;
={test(),test(1),test(3,4),test(5,6,7)};
cout<<"c is "<<c;
}};
cout<<"z objects "<<endl;
for(i=0;i<=3;i++)
z[i].showdata();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


z objects 162
x objects y objects
a is 0
a is 0
a is 1 b is 0 z[0]
b is 0 y[0]
x[0] b is 2 c is 0
c is 0
c is 0

a is 0 a is 1
b is 0 a is 3 b is 1 z[1]
c is 0 b is 4 y[1] c is 1
x[1]
c is 0
a is 0 a is 3
b is 0 a is 5 b is 4 z[2]
y[2]
c is 0 x[2] b is 6 c is 0
c is 0
a is 5
b is 6 z[3]
c is 7

(PN) (MCA)(2010-11/ EVEN) (2010-13)


163

Pointers to Object Members

The syntax for defining the pointer to class member and binding
the class member to the pointer is shown below

Pointer to a member of a class

datatype classname::*pointername;

Address of a member of a class

pointername =&classname :: member;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


164

class test
{
private:
int x;
public:
int a,b;
int init(int z);
int check(int c);
};

A pointer to the member a or b is defined as follows:

int test::*ip;

The address of the member can be assigned by

ip=&test::a;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


165

The address of the member a can also be assigned to a pointer


during its definition as

int test::*ip=&test::a;

The pointer variable ip, acts like the class member so that it can
be invoked with a class object

The address of the private member x cannot be assigned by


using the statement ip=&test::x; // illegal

Private members have the same access control privilege even


with a pointer to the class members

(PN) (MCA)(2010-11/ EVEN) (2010-13)


166

 Normal pointer variable cannot be used as a pointer to the class


member. Hence the statement int *ptr=&test::a; is invalid

 The pointer and the variable have meaning only when they are
associated with the class to which they belong

 The scope resolution operator must be applied to both the


pointer and the member

(PN) (MCA)(2010-11/ EVEN) (2010-13)


167

 Like pointers to data members, pointer to member function can also be


defined and invoked using dereferencing operator

A pointer to a member function show() is defined as follows

int (test::*func_ptr)(int);

The address of the member show() can be assigned by

func_ptr=&test:: show;

or

int(test::*func_ptr)(int)=&test:: show;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


168

Different methods of accessing class data member

 Common way of accessing a class data member


Objectname.Member;

 Accessing class data member through its pointer


Objectname.*PointerToMember;

 Accessing class data member through the pointer to object


PointerToObject->Member;

 Accessing class data member through the pointer to object &


member
PointerToObject->*PointerToMember;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


169

Different methods of accessing class member function

 Common way of accessing a class member function


Objectname.Member(arguments);

 Accessing class member function through the pointer to object


PointerToObject->Member(arguemnts);

 Accessing class member function through its pointer


(Objectname.*PointerToMember)(arguments);

 Accessing class member function through the pointer to object &


member
(PointerToObject->*PointerToMember)(arguemnts);

(PN) (MCA)(2010-11/ EVEN) (2010-13)


class test { public: int a; test() { a=100; } 170
int mul(int k1) { a=k1; return a*a; }
};
void main() {
test t1; test *ptr1;
ptr1=&t1; int test::*ptr2=&test::a;
cout<<"common way of accessing a data member"<<t1.a;
cout<<“accessing data member through the pointer to object"<<ptr1->a;
cout<<“accessing data member through its pointer "<<t1.*ptr2;
cout<<"accessing data member through the pointer to object and member
"<<ptr1->*ptr2;
int (test::*funptr)(int)=&test::mul;
cout<<"common way of accessing a data member fn. "<<t1.mul(10);
cout<<"accessing member fn. through the pointer to object"<<ptr1->mul(20);
cout<<"accessing member fn. through its pointer "<<(t1.*funptr)(30);
cout<<"accessing member fn.through the pointer to object and member
"<<(ptr1->*funptr)(40);
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


171

common way of accessing a data member 100


accessing data member through the pointer to object 100
accessing data member through its pointer 100
accessing data member through the pointer to object and member100

common way of accessing a member fn. 100


accessing member fn. through the pointer to object 400
accessing member fn. through its pointer 900
accessing member fn.through the pointer to object and member 1600

(PN) (MCA)(2010-11/ EVEN) (2010-13)


172

Pointer to Private Members

class myclass { void main() {


private: int a,b; myclass m1;
friend int add(myclass &m) void (myclass::*func_ptr)(int,int);
public:
func_ptr=&myclass::setab;
void setab(int k1,int k2){
(m1.*func_ptr)(15,16);
a=k1;b=k2; }
cout<<“Sum is="<<add(m1);
};
myclass *ptrtoobj=&m1;
int add(myclass &m) {
int myclass::*pa=&myclass::a;
(ptrtoobj->*func_ptr)(20,25);
int myclass::*pb=&myclass::b; cout<<“Sum is="<<add(m1);
myclass *ptr=&m; }
return m.*pa+ptr->*pb; Sum is 31
} Sum is 45

(PN) (MCA)(2010-11/ EVEN) (2010-13)


173

Operator Overloading – Compile time Polymorphism

 C++ supports a set of operators for built-in types. For example,


x = y+1; ‘+’ operates on both y and 1

 Similarly, it is possible to define new operators that work with


classes

 This definition is just like an ordinary function definition except


that the name of the function consists of the keyword operator
followed by the operator

 Operator overloading enhances the program readability


without the loss of functionality

(PN) (MCA)(2010-11/ EVEN) (2010-13)


174

For instance the statement


C3 = AddComplex(C1,C2); or C3.AddComplex(C1,c2);
performs the addition of operands C1 and C2 belonging to the
user defined data type and assigns result to C3 (which is also a
user defined data type).

In C++, by overloading the ‘+’ operator, the above statement can


be changed to an easily readable form.

If c1 and c2 are two object of a class ‘Complex’, then C3=C1+C2;


is a valid statement which performs the addition of operands c1
and c2 and assigns result to c3.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


175

 The operator overloading feature of C++ is one of the methods


of realizing polymorphism

 Here, poly refers to many or multiple and morphism refers to


actions i.e. performing many actions to a single operator

 As stated earlier, the + operator performs integer addition if


the operands are of integer type and floating point addition if
the operand are of real type etc.,

(PN) (MCA)(2010-11/ EVEN) (2010-13)


176
 The concept of operator overloading can also be applied to data
conversion

 C++ offers automatic conversion of primitive data types, for


example int a,b; float x; In the statement x=a+b; the
compiler implicitly converts the integer result to floating point
representation and then assigns to float variable x

 But the conversion of user defined data types requires some


effort on part of the programmer

 Thus operator overloading concepts are applied to the following


two principle areas
 Extending capability of operators to operate on user
defined data
 Data Conversion

(PN) (MCA)(2010-11/ EVEN) (2010-13)


177

Rules for Overloading Operators

 Only predefined operator can be overloaded. New


operators cannot be created

 The overloaded operator must have at least one


operand that is of user-defined type

 We cannot change the basic meaning of an operator.


To be exact, we cannot redefine the plus (+)
operators to subtract the value from the other

 Overloaded operators follow the syntax rules of the


original operators. They cannot be overridden

(PN) (MCA)(2010-11/ EVEN) (2010-13)


178
Overloadable Operators
Operator Category Operators
Arithmetic +-* /%
Bit-wise &|~^
Logical && || !
Relational < > <= >= != ==
Assignment =
Arithmetic Assignment += -= *= /= %= |= ^=
Shift << >> <<= >>=
Unary ++ --
Subscripting []
Function Call ()
Dereferencing ->
Unary Sign Prefix +-
Allocate and Free new,delete

(PN) (MCA)(2010-11/ EVEN) (2010-13)


179

All Operators cannot be Overloaded

Operator Category Operators


Member Access . (dot operator)
Scope resolution :: (global access)
Conditional ?: (conditional Statement)
Pointer to member *
Size of Data Type sizeof()

(PN) (MCA)(2010-11/ EVEN) (2010-13)


180

Creating a Member Operator Function

A member operator function takes this general form:


ret-type class-name :: operator#(arg-list)
{
// body of function
}
# can be any valid unary or binary operator.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


181

Overloading Unary Operators

Syntax for overloading unary operator

(PN) (MCA)(2010-11/ EVEN) (2010-13)


182
class index {
int value;
public:
index ()
void main() {
{ value=0; } index idx1,idx2;
int get_index() cout<<“\n index1=“<<idx1.get_index();
{return value;}
cout<<“\n index2=“<<idx2.get_index();
void next_index() idx1.next_index();
{value+= 1;}
}; idx2.next_index();
idx2.next_index();
index 1 0
index 2 0 cout<<“\n index1=“<<idx1.get_index();
index 1 1
index 2 2 cout<<“\n index2=“<<idx2.get_index();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


183
void main() {
class index {
index idx1,idx2;
int value;
cout<<“\n index1=“<<idx1.get_index();
public:
cout<<“\n index2=“<<idx2.get_index();
index ()
++idx1;
{ value=0; }
idx2++;
int get_index()
idx2++;
{return value;}
cout<<“\n index1=“<<idx1.get_index();
void operator ++()
cout<<“\n index2=“<<idx2.get_index();
{value+= 1; }
}
};

index 1 0
index 2 0
index 1 1
index 2 2

(PN) (MCA)(2010-11/ EVEN) (2010-13)


184

Limitation of unary operator

In the above program ++operator function is invoked for


both pre-increment and post-increment; there is no distinction in
invocation; it can be overcome by defining two version for the
++operator function

(PN) (MCA)(2010-11/ EVEN) (2010-13)


185
void main() {
class index { index idx1,idx2,idxpost,idxpre;
int value; cout<<"index1
"<<idx1.get_index();
public: cout<<" index2
index ( ) { value=0; } "<<idx2.get_index();
index(int val) { value=val; } idxpost=idx1++;
cout<<" index post is
int get_index(){return value ; } "<<idxpost.get_index();
index operator ++ ();//pre cout<<" index1
index operator ++(int);//post "<<idx1.get_index();
idxpre=++idx2;
}; cout<<" index pre is
index index:: operator ++ () { "<<idxpre.get_index();
return index (++value); } cout<<" index2
"<<idx2.get_index(); }
index index:: operator ++ (int) { index1 0 index2 0
return index (value++); } index post is 0 index1 1
index pre is 1 index2 1

(PN) (MCA)(2010-11/ EVEN) (2010-13)


186

Binary Operator Overloading

 The concept of overloading applies to binary operator too

 The binary overloaded operator function takes the first


operand as an implicit operand and the second operand must
be passed explicitly.

 The data members of the first operand are accessed without


using the dot operator whereas, the second argument
members can be accessed using the dot operator if the
argument is an object.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


187

Syntax for overloading binary operator

(PN) (MCA)(2010-11/ EVEN) (2010-13)


188

class complex {
float x,y;
public: void main()
complex() { } complex c1(1.5,2.5),c2(1.7,2.6);
complex(float x1,float y1){ complex c3;
x=x1;y=y1;}
c3=c1+c2;
void show() {
cout<<"C1 = ";c1.show();
cout<< x<<" + j"<< y }
complex operator+(complex&); cout<<"C2 = ";c2.show();
}; cout<<"C3 = ";c3.show();
complex complex::operator + }
(complex &obj2) {
float x1,y1;
x1=x+obj2.x; y1=y+obj2.y; C1 = 1.5 + j2.5
return complex(x1,y1); C2 = 1.7 + j2.6
} C3 = 3.2 + j5.1

(PN) (MCA)(2010-11/ EVEN) (2010-13)


189

Overloading with Friend Function

 this is a pointer to the current object from which it is used

 To use a friend function to overload the unary operators, you


must pass the operand as a reference parameter, because
friend functions do not have this pointer

 Since the friend operator function is passed as a copy of the


operand and not as this pointer to the operand, no changes
are made to that parameter affect by the operand that
generated the call

 You can overcome the problem by specifying the parameter


to the friend operator function as a reference parameter

(PN) (MCA)(2010-11/ EVEN) (2010-13)


190

class index {
int value;
public:
index ( ) { value=0;
void main() {
}
int get_index(){return value; } index idx1,idx2;
friend void operator++(index i1); cout<<“ index1
}; "<<idx1.get_index();
void operator ++ (index i1) { cout<<" index2
i1.value =i1.value + 1; } "<<idx2.get_index();
++idx1;
index 1 0 idx2++;
index 2 0
idx2++;
index 1 0
index 2 0
cout<<" index1
"<<idx1.get_index();
cout<<"index2“
<<idx2.get_index();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


191

class index { void main() {


int value;
index idx1,idx2;
public:
index ( ) { value=0;
cout<<“ index1
} "<<idx1.get_index();
int get_index(){return value; } cout<<" index2
friend void operator++(index &i1); "<<idx2.get_index();
}; ++idx1;
void operator ++ (index &i1) { idx2++;
i1.value =i1.value + 1; } idx2++;
cout<<" index1
index 1 0
index 2 0
"<<idx1.get_index();
index 1 1 cout<<"index2“
index 2 2 <<idx2.get_index();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


192

void main() {
class complex{ complex c1(1.5,2.5),c2(1.7,2.6);
float x,y; complex c3;
public:
complex() { }
c3=c1+c2;
complex(float x1,float y1){ cout<<"C1 = ";c1.show();
x=x1;y=y1;} cout<<"C2 = ";c2.show();
void show() { cout<<"C3 = ";c3.show();
cout<< x<<" + j"<< y ; }
friend complex operator +
}
(complex &,complex&);
}; C1 = 1.5 + j2.5
complex operator + C2 = 1.7 + j2.6
(complex &obj1,complex &obj2) {
float x1,y1; C3 = 3.2 + j5.1
x1=obj1.x+obj2.x;
y1=obj1.y+obj2.y;
return complex(x1,y1); }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


193

Why Friend for Operator Overloading?

 Operator member function and friend function is capable of


handling user defined and primitive data type as their
arguments

 The only difference between them is that friend function can


handle both this invocation

c3=c1+2.0; or c3= 2.0+c1; both are valid

Whereas c3=2.0+c1; is invalid in operator member function

(PN) (MCA)(2010-11/ EVEN) (2010-13)


194
complex operator +
(complex obj1,complex obj2) {
class complex{ float x1,y1;
float x,y; x1=obj1.x+obj2.x;
public: y1=obj1.y+obj2.y;
complex() { } return complex(x1,y1); }
complex (float realpart) {
x=y=realpart; }
complex(float x1,float y1){
x=x1;y=y1;}
void show() {
cout<< x<<" + j"<< y ; }
friend complex operator +
(complex,complex);
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


195
void main() {
complex c1(1,2),c2(3,4); C1 = 1 + j2
complex c3; C2 = 3 + j4
c3=c1+c2; C3 = 4 + j6
cout<<"\n C1 = ";c1.show(); C3 = 3 + j4
cout<<"\n C2 = ";c2.show(); C3 = 3 + j4
cout<<"\n C3 = ";c3.show();
c3=c1+2.0;// c1+ complex(2.0);
cout<<"\n C3 = ";c3.show();
c3=2.0+c1;// complex(2.0)+c1;
cout<<"\n C3 = ";c3.show();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


196

class complex{ complex complex::operator


float x,y; +(complex obj2) {
public: float x1,y1;
complex() { } x1=x+obj2.x;
complex (float realpart) y1=y+obj2.y;
{x=y=realpart;} return complex(x1,y1);
complex(float x1,float y1){ }
x=x1;y=y1;}
void show(){
cout<< x<<" + j"<< y ; }
complex operator +(complex);
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


197

void main() {
complex c1(1,2),c2(3,4);
complex c3;
c3=c1+c2;
cout<<"\n C1 = ";c1.show();
cout<<"\n C2 = ";c2.show();
cout<<"\n C3 = ";c3.show();
c3=c1+2.0;// c1+ complex(2.0)
cout<<"\n C3 = ";c3.show();
//c3=2.0+c1; invalid
cout<<"\n C3 = ";c3.show();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


198

class complex{ complex complex::operator


float x,y; +(float temp) {
public: float x1,y1;
complex() { } x1=x+temp;
complex (float realpart) y1=y+temp;
{x=y=realpart;} return complex(x1,y1);
complex(float x1,float y1){ }
x=x1;y=y1;}
void show(){
cout<< x<<" + j"<< y ; }
complex operator +(float);
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


199

void main() {
complex c1(1,2),c2(3,4);
complex c3;
c3=c1+c2;
cout<<"\n C1 = ";c1.show();
cout<<"\n C2 = ";c2.show();
cout<<"\n C3 = ";c3.show();
c3=c1+2.0;// no object creation; direct floating point data
cout<<"\n C3 = ";c3.show();
// invalid c3=2.0+c1;
cout<<"\n C3 = ";c3.show();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


class complex{ 200
float x,y;
public:
complex() { }
complex (float realpart)
{x=y=realpart;}
complex(float x1,float y1){
x=x1;y=y1;}
void show(){
cout<< x<<" + j"<< y ; }
//complex operator +(float);
complex operator +(complex &);
Ambiguity
friend complex operator+(float,complex &);
friend complex operator+(complex &,float);
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


201
/*complex complex::operator +(float temp)
{float x1,y1; x1=x+temp; y1=y+temp; return complex(x1,y1); }*/

complex complex::operator +(complex &c2)


{float x1,y1; x1=x+c2.x; y1=y+c2.y; return complex(x1,y1);}

complex operator +(float t,complex &c2)


{float x1,y1; x1=t+c2.x; y1=t+c2.y; return complex(x1,y1); }

complex operator +(complex &c2,float t)


{ float x1,y1; x1=t+c2.x; y1=t+c2.y; return complex(x1,y1); }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


202

void main() {
complex c1(1,2),c2(3,4);
complex c3;
c3=c1+c2;
cout<<"\n C1 = ";c1.show();
cout<<"\n C2 = ";c2.show();
cout<<"\n C3 = ";c3.show();
c3=c1+2.0;// no object creation; direct floating point data
cout<<"\n C3 = ";c3.show();
c3=2.0+c1;
cout<<"\n C3 = ";c3.show();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


203

Overloading [] Operator

class Array { class Array {
private: private:
   int data[100];    int data[100];  
public: public:
   int& operator[] (unsigned i) 
int& elem(unsigned i)
{ if (i > 99) 
{ if (i > 99)
cout<<“error out of range”; 
cout<<“error out of range”;  
return data[i]; 
return data[i]; 
}
}  }; 
   };  
void main() void main()
 {  {
Array a;    Array a;
a.elem(10) = 42;    a[10] = 42;
a.elem(12) += a.elem(13)    a[12] += a[13];
;    ...
   ...  }
}
(PN) (MCA)(2010-11/ EVEN) (2010-13)
204

Manipulation of Strings Using Operators

#include<string.h> String String::operator +(String ss){


const int size =100;
if(strlen(str) + strlen(ss.str)<size)
class String {
{String temp=str;//strcpy(temp.str,str);
char str[size];
public: strcat(temp.str,ss.str);
String() { } return temp; }
String(char *s) else
{strcpy(str,s); } {String ftemp("String overflow");
void show(); return ftemp; }
String operator+(String); }
int operator < (String);
};
int String::operator < (String ss)
void String::show() { {return strlen(str)<strlen(ss.str)?1:0;}
cout<<'\''<<str<<'\''; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


205

void main() {
String str1("Welcome to ");
String str2("India");
String str3;
cout<<"String1 is :";str1.show();
cout<<"\nString2 is :";str2.show();
str3=str1+str2;
cout<<"\nString3 is :";str3.show();cout<<endl<<endl;
if(str1 < str3) {
str1.show();
cout<<"is smaller than "; str3.show(); }
else{str3.show();cout<<"is smaller than ";str1.show(); }
}
String1 is :'Welcome to '
String2 is :'India'
String3 is :'Welcome to India‘ +
'Welcome to 'is smaller than 'Welcome to India‘ <

(PN) (MCA)(2010-11/ EVEN) (2010-13)


206

Overloading new and delete operators


It is possible to overload new and delete
// Allocate an object
void *operator new(size_t size)
{
/* Perform allocation.
Constructor called automatically. */
return pointer_to_memory;
}
// Delete an object
void operator delete(void *p)
{
/* Free memory pointed to by p.
Destructor called automatically. */
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


 The type size_t is capable of containing the largest single piece 207
of memory that can be allocated

 Size_t is essentially an unsigned integer

 The parameter size will contain the number of bytes needed


to hold the object being allocated

 This is the amount of memory that your version of new must


allocate

 The overloaded new function must return a pointer to the


memory that it allocates, or throw a bad_alloc exception if an
allocation error occurs

 Whey you allocate an object using new (whether your own


version or not), the object constructor is automatically called

(PN) (MCA)(2010-11/ EVEN) (2010-13)


208

The delete function receives a pointer to the region of the


memory to be freed

It then releases the previously allocated memory back to the


system

When an object is deleted, its destructor is automatically


called

(PN) (MCA)(2010-11/ EVEN) (2010-13)


209

void allot::operator delete(void *p)


class allot { {cout<<"In overload delete";
int x,y;
free(p);}
public:
void main() {
allot() { x=y=0; }
allot(int a,int b) {
allot *a1,*a2;
x=a;y=b; } a1=new allot();
void show() { a2=new allot(5,6);
cout<<"x is :"<<x<<“ y is :"<<y; } a1->show(); a2->show();
void* operator new(size_t size); delete a1; delete a2; }
void operator delete(void *p); In overload new
};
In overload new
void* allot::operator new(size_t size){
x is :0 y is :0
cout<<" In overload new"; void *p;
p=malloc(size); return p; } x is :5 y is :6
In overload delete
In overload delete

(PN) (MCA)(2010-11/ EVEN) (2010-13)


210

Overloading new and delete globally

 When new and delete operators are for a specific class, the
use of these operators on any other type of data causes the
original new or delete to be employed

 The overloaded operators are only applied to the types for


which they are defined
If you add this line to main(), the default new will be
executed:
int *f=new float; //uses default new

 You can overload new and delete globally by overloading


these operators outside of any class declaration by stand
alone function

(PN) (MCA)(2010-11/ EVEN) (2010-13)


211

 When new and delete are overloaded globally , C++’s default


new and delete are ignored and the overridden new and delete
operators are used for all allocation and de-allocation requests

 In other words, when new or delete are encountered, the


compiler first checks to see whether they are defined relative
to class they are operating on

 If so, those specific versions are used, if not, C++ uses the
globally defined new and delete

 If there is no explicitly overloaded versions at all, C++ default


new and delete will be invoked for the requisition

(PN) (MCA)(2010-11/ EVEN) (2010-13)


class loc { p2 = new loc (-10, -20); 212
int longitude, latitude; f=new float;//uses overloaded new, too
public:
p1->show(); p2->show();
loc() {}
loc(int lg, int lt) { *f = 10.10F; cout << *f;
longitude = lg; latitude = lt; } delete p1; delete p2;delete f; }
void show() { In global new:
cout << longitude<<latitude "; } };
In global new:
// Global new
void *operator new(size_t size) { In global new:
cout<<" In global new:"; void *p; 10 20
p = malloc(size); return p; } -10 -20
// Global delete 10.1
void operator delete(void *p) {
In global delete:
cout<<"In global delete:"; free(p); }
void main() { In global delete:
loc *p1, *p2; float *f; In global delete:
p1 = new loc (10, 20); In global delete:
In global delete:

(PN) (MCA)(2010-11/ EVEN) (2010-13)


213

Overloading new and delete for Arrays


If you want to be able to allocate arrays of objects using your
own allocations system, you will need to overload new and delete
a second time
// Allocate an array of objects
void *operator new[](size_t size)
{
/* Perform allocation,Constructor for each called automatically.*/
return pointer_to_memory;
}
// Delete an array of objects
void operator delete[](void *p)
{
/* Free memory pointed to by p,Destructor for each element called
automatically. */
}
(PN) (MCA)(2010-11/ EVEN) (2010-13)
214

class loc { //new overloaded relative toloc.


int longitude, latitude; void *loc::operator new(size_t size)
public: {void *p; p=malloc(size); return p;}
loc() {longitude = latitude= 1;} //delete overloaded relative to loc.
loc(int lg, int lt) { void loc::operator delete(void *p)
longitude = lg; latitude = lt; } {free(p); }
void show() { // new overloaded for loc arrays.
cout << longitude << " "; void *loc::operator new[](size_t size)
cout << latitude << "\n"; } {void *p; p=malloc(size); return p;}
void *operator new(size_t size);// delete overloaded for loc arrays.
void operator delete(void *p); void loc::operator delete[](void *p)
void *operator new[](size_t size); { free(p); }
void operator delete[](void *p);};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


215
Go to slide 181
void main() {
loc *p1, *p2; int i;
p1 = new loc (10, 20); // allocate an object 10 20
p2 = new loc [10]; // allocate an array 11
p1->show(); 11
for (i=0; i<10; i++) 11
p2[i].show(); 11
delete p1; // free an object 11
delete [] p2; // free an array 11
} 11
11
11
11

(PN) (MCA)(2010-11/ EVEN) (2010-13)


216

Data Conversion – Conversion between basic types

 Consider the statement


weight =age; // weight is of float type and age is of int type
Here the complier calls a special routine to convert the value of
age ,which is represented in an integer format, to a floating
point format, so that it can be assigned to weight

 The compiler has several built-in-routines for the conversion of


basic data types such as char to int , float to double etc

 This feature of the compiler, which performs conversion of data


without user intervention is known as implicit type conversion

(PN) (MCA)(2010-11/ EVEN) (2010-13)


217

 The complier can be instructed explicitly to perform type


conversion using the type conversion operator known as
typecast operators

For ex: weight = (float) age; or weight = float (age);

 The explicit conversion of float to int uses the same built-in


routines as implicit conversion

(PN) (MCA)(2010-11/ EVEN) (2010-13)


218

Conversion between Objects and Basic Types

constructor (basic type)


{
// steps for converting basic type to object attributes
}

Conversion function: basic to user-defined

(PN) (MCA)(2010-11/ EVEN) (2010-13)


219

operator basic type()


{
// steps for converting object attributes to basic type
}

Conversion function: user-defined to basic

(PN) (MCA)(2010-11/ EVEN) (2010-13)


220

class meter {
float length;
public:
meter() { length=0.0;}
meter(float initlength) {//one argument constructor,converts
length=initlength/100.0; // centimeter to meter
}
operator float() {//converts meter to centimeter
return length*100.0; }
void getlength() { cout<<"\n enter length (in meters): ";
cin>>length; }
void showlength() {cout<<"\n length (in meter)= "<<length; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


221

void main() {
meter m1; // uses constructor0
float length1,length2;
cout<<"\n enter length in centimeter :"; cin>>length1;
m1=length1;// converts basic to userdefined, uses constructor1
m1.showlength();
meter m2; m2.getlength();
length2=m2;//converts userdefined to basic,uses operator float()
cout<<"\n length (in cms) ="<<length2; }

enter length in centimeter :450


length (in meter)= 4.5
enter length (in meters): 3.2
length (in cms) =320

(PN) (MCA)(2010-11/ EVEN) (2010-13)


222

Conversion between Objects of Different Classes

The C++ compiler does not support data conversion between


objects of user-defined classes

It is possible to do data conversion by either one argument


constructor and conversion function or overloading = operator
through class member function

(PN) (MCA)(2010-11/ EVEN) (2010-13)


223

Data conversion using one argument constructor and


conversion function

Example:
Angle in Radian = Angle in Degree*PI/180.0
Angle in Degree = Angle in Radian *180/PI, where PI=22/7

In an assignment statement such as, objecta =objectb;


objectb is the source object of the class ClassB and objecta is
the destination object of the class ClassA. The conversion
operator ClassA() exists in source object’s class.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


224
Syntax for Conversion routine in Source Object :
operator function

class ClassA // destination object class


{
//ClassA stuff here
}
class ClassB // source object class
{
private: Destination object’s class name
// attribute of ClassB
public:
operator ClassA() Conversion operator function
{
// program stuff for converting ClassB object to ClassA object
}
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


225

class degree {
const float PI = 3.1415;
float deg;
class radian {
public:
float rad;
degree() { deg=0.0; }
public:
operator radian() {
radian() { rad=0.0;}
return radian(deg*PI/180.0); }
radian(float initrad) {
void showdata() {
rad=initrad; }
cout<<"\n Degree= "<<deg; }
void showdata() {
void getdata() {
cout<<"\n Radian = "<<rad; }
cout<<"enter degree :";
};
cin>>deg; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


226

void main() {
degree deg1; radian rad1;
deg1.getdata();
rad1=deg1;
rad1.showdat a();
}

enter degree :90


Radian = 1.57075

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Syntax for Conversion routine in Destination Object : 227

one argument constructor


class ClassB // source object class
{
//ClassB stuff here
}
class ClassA // destination object class
{
private: Destination object’s class name
// attribute of ClassA
public: Object of source class
ClassA(ClassB objectb) Constructor function
{
//program stuff for converting ClassB object to ClassA object,
//private attributes of ClassB are accessed through its public function
}
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


228

class radian {
const float PI = 3.1415;
float rad;
class degree {
public:
float deg;
radian() { rad=0.0;}
public: radian(float initrad) {
degree() { deg=0.0; } rad=initrad; }
void getdata() { radian(degree d) {
cout<<"enter degree :"; rad=d.getdegree()*PI/180.0; }
cin>>deg; } float getradian() {
float getdegree(){return deg; } return rad; }
}; void showdata() {
cout<<"\n Radian = "<<rad; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


229

void main() {
degree deg1; radian rad1;
deg1.getdata();
rad1=deg1;
rad1.showdata();
}

enter degree :90


Radian = 1.57075

(PN) (MCA)(2010-11/ EVEN) (2010-13)


230

Complete Conversion

const float PI = 3.1415; class degree {


class radian { float deg;
float rad; public:
public: degree() { deg=0.0; }
radian() { rad=0.0;} degree(radian r) {
radian(float initrad) { deg=r.getradian()*180/PI; }
rad=initrad;} operator radian() {
float getradian(){ return rad; } return radian(deg*PI/180.0); }
void getdata(){ void showdata() {
cout<<"enter radian :"; cout<<"Degree= "<<deg; }
cin>>rad; } void getdata() {
void showdata() { cout<<"enter degree:"; cin>>deg;
cout<<"Radian = "<<rad; } }
}; };

(PN) (MCA)(2010-11/ EVEN) (2010-13)


231

void main() {
degree deg1,deg2; radian rad1,rad2;
//degree to radian conversion
deg1.getdata();
rad1=deg1; // convert degree to radian, uses ‘operator radian()’
rad1.showdata();
//radian to degree conversion
rad2.getdata();
deg2=rad2; // convert radian to degree, uses degree(radian r)
deg2.showdata(); }
enter degree :90
Radian = 1.57075
enter radian :1.57075
Degree= 90

(PN) (MCA)(2010-11/ EVEN) (2010-13)


232

Data conversion using overloading = operator through class


member function

class kilogram;//forward decl


class pound { class kilogram {
float pnds; float kg;
public: public:
pound() { pnds=0.0; } kilogram() {kg=0.0;}
pound(float pns){pnds=pns;} kilogram(float kms) {kg=kms; }
void showdata(char *msg) { void showdata(char *msg) {
cout<<"\n"<<msg<<pnds<<" cout<<"\n"<<msg<<kg<<"
pounds \n";} kilogram \n"; }
float getpound(){return pnds;} float getkilogram() {return kg; }
void operator=(kilogram); void operator=(pound);
}; };

(PN) (MCA)(2010-11/ EVEN) (2010-13)


233

void pound::operator=(kilogram k1){pnds=2.2*k1.getkilogram();}


void kilogram::operator=(pound p1){kg=0.4536*p1.getpound();}
void main(){
cout<<"\n 1 kilogram is = 2.2 pound";
cout<<"\n 1 pound is = 0.4536 kilogram";
pound p(6.6); kilogram k(4.5);
k.showdata("\n i am kilogram object k, ");
p.showdata("\n i am pound object p, ");
pound ps; kilogram km;
km=p;
ps=k;
ps.showdata("i am pound object ps built by kilogram object k ,4.5 kg is ");
km.showdata("i am kilogram object km built by pound object p, 6.6 pound is ");

(PN) (MCA)(2010-11/ EVEN) (2010-13)


234

1 kilogram is = 2.2 pound


1 pound is = 0.4536 kilogram

i am kilogram object k, 4.5 kilogram


i am pound object p, 6.6 pounds

i am pound object ps built by kilogram object k ,4.5 kg is 9.9 pounds

i am kilogram object km built by pound object p,6.6 pound is 2.99376


kilogram

(PN) (MCA)(2010-11/ EVEN) (2010-13)


235

Inheritance and Composition : Code Re-usability

 One of the most compelling features about C++ is code reuse

 Everything in C++, the solution revolves around the class

 You reuse code by creating new classes, but instead of creating


them from scratch, you use existing classes that has already built

 The trick is to use the classes without soiling the existing code

 The 2 ways to accomplish this idea are inheritance and composition

(PN) (MCA)(2010-11/ EVEN) (2010-13)


236

 The first is quite straightforward; You simply create objects of your


existing class inside the new class

 This is called composition, because the new class is composed of


objects of existing classes

 The second approach is subtler, You create a new class as a type of


an existing class

 You literally take the form of the existing class and add code to it,
without modifying the existing class

 This magical act is called inheritance, and most of the work is done
by the compiler.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


237

Composition
class Y {
class X {
int i;
int i;
public:
public:
X x;
X() { i = 0; }
Y() { i = 0; }
void set(int ii) { i = ii; }
void f(int ii) { i = ii; }
int read() const { return i; }
int g() const { return i; }
int permute() {return i = i * 47; }
};
};
void main() {
Y y; y.f(47);
y.x.set(37);
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


238
Composition to more depth
class X { class Y {
class Z {
int i; int i;
int i;
public: public:
public:
Z z; X x;
Z() { i=0;}
X() { i = 0; } Y() { i = 0; }
void set(int ii)
void set(int ii) void f(int ii)
{ i = ii; }
{ i = ii; } { i = ii; }
void show()
int read() const int g() const
{
{ return i; } { return i; }
cout<<" i from z class
int permute() };
is"<<i;
{return i = i * 47; }
}
};
}; void main() {
Y y;
y.f(20);
y.x.set(13);
y.x.z.show();
}
(PN) (MCA)(2010-11/ EVEN) (2010-13)
239

Composition -Private

class Y {
int i;
class X { X x;
int i; public:
public: Y() { i = 0; }
X() { i = 0; } void f(int ii) {i=ii; x.set(ii);}
void set(int ii) { i = ii; } int g()const {return i *x.read(); }
int read() const { return i; } void permute() { x.permute(); }
int permute() {return i = i * 47; } };
}; void main() {
Y y; y.f(47);
y.permute();
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


240

Inheritance

class Y : public X{
int i;
class X { public:
int i; Y() { i = 0; }
public: void f(int ii) { i = ii; }
X() { i = 0; } int g() const { return i; }
void set(int ii) { i = ii; } };
int read() const { return i; } void main() {
int permute() {return i = i * 47; } Y y;
}; y.f(47);
y.set(37);
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


241
Forms of Inheritance

(PN) (MCA)(2010-11/ EVEN) (2010-13)


242

The Class Derivation

 When you declare a class, you can indicate the name of the
class from which it derives

 It can be done by providing a colon after the derived class


name, after that the visibility mode and the base class name
from which it derives

Syntax
class derived class name : visibility mode base class name
{
… // Members of derived class
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


243

Visibility Mode

 The visibility mode is optional and if present, may be


either private, public, or protected

 Visibility mode specifies whether the members of the


base class are derived as either private, public, or
protected

For example:
class ABC : private XYZ // private derivation
{
Members of ABC
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


244

Visibility Mode (Contd..)

class ABC : public XYZ // public derivation


{
Members of ABC
};

class ABC : XYZ // private by default


{
Members of ABC
};
class ABC : protected XYZ
{
Members of ABC
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


245

Visibility of Inherited Members

Derived Class Visibility


Base Class
Visibility Public Private Protected
Derivation Derivation Derivation
Not
Private Not Inherited Not Inherited
Inherited
Protected Protected Private Protected

Public Public Private Protected

Go to slide 69

(PN) (MCA)(2010-11/ EVEN) (2010-13)


246

Effect of Inheritance on the visibility of members


class B
Not inheritable Not inheritable

class D1:public B class D2:private B

class X: public D1:protected D2

(PN) (MCA)(2010-11/ EVEN) (2010-13)


A 247
pb pr
pv
class A { B C D
private: int privatedataA; public: int publicdataA;
protected: int protecteddataA;};
class B: public A // publicly inherited
{ public: void assign() { int a; //local variable
//a=privatedataA; a=protecteddataA; a=publicdataA; } };
class C : private A {
public: void assign() { int a;
// a=privatedataA;a=protecteddataA; a=publicdataA; } };
class D : protected A
{ public: void assign() { int a;
// a=privatedataA; a=protecteddataA;a=publicdataA; }};
void main() {
int a; B objB; C objC; D objD;
//a=objB.privatedataA;//a=objB.protecteddataA; a=objB.publicdataA;
//a=objC.privatedataA;//a=objC.protecteddataA;// a=objC.publicdataA;
//a=objD.privatedataA;//a=objD.protecteddataA; // a=objD.publicdataA;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


248
Publicizing Privately inherited
class A {
private: int privatedataA; public: int publicdataA;
protected: int protecteddataA; };
class B: private A
{
protected:
A::protecteddataA; // protectedsizing privately inherited protecteddataA
public:
A::publicdataA; // publicizing privately inherited publidataA
void assign() {
int a;
//a=privatedataA; // Error: not accessible
a=protecteddataA; // Ok
a=publicdataA; // Ok
}
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


class C : public B { 249
public:
void assign() {
int a;
// a=privatedataA; // Error: not accessible
a=protecteddataA; // Ok
a=publicdataA; // Ok
}
};

void main() {
C c1;
cout<<c1.publicdataA;
B b1;
cout<<b1.publicdataA;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


250

Constructors in Derived Classes

 The derived class need not have a constructor as long as


the base class has a no-argument constructor

 However, if the base class has parameterized constructors


then it is mandatory for the derived class to have a
constructor and pass the arguments to the base class
constructor

(PN) (MCA)(2010-11/ EVEN) (2010-13)


251

No constructors in base and derived class


class B {
// body of base class without constructors
};
class D: public B {
public:
void msg() {
cout<<“No constructors exists in both base and derived class”; }
};
void main() {
D objd; objd.msg(); }

No constructors exists in both base and derived class

(PN) (MCA)(2010-11/ EVEN) (2010-13)


252

Constructors only in the base class

class B {
public:
B()
{cout<<“No argument constructor of the base class B is executed”;}
};
class D: public B {
};
void main() {
D obj1;
}

No argument constructors of the base class B is executed

(PN) (MCA)(2010-11/ EVEN) (2010-13)


253

Constructors only in the derived class

class B {
// body of base class without constructors
};
class D: public B {
public:
D() {cout<<“constructors exists in only in derived class”;}
};
void main() {
D objd; }

constructors exists in only in derived class

(PN) (MCA)(2010-11/ EVEN) (2010-13)


254

Constructors in both base and derived classes

class B {
public:
B() {
cout<“No-argument constructor of the base class B executed first”; }
};
class D: public B {
public:
D() {
cout<<“No-arg constructor of the derived class D executed next”; } };
void main() { D objd; }
No-argument constructor of the base class B executed first
No-argument constructor of the derived class D executed next

(PN) (MCA)(2010-11/ EVEN) (2010-13)


255

Multiple Constructors in base class and a single


constructor in derived classes

class B {
public:
B() {cout<“No-argument constructor of the base class B ”; }
B(int a){cout<“one argument constructor of the base class B ”; }
};
class D: public B {
public:
D(int a){cout<“one argument constructor of the derived class D ”; }
};
void main() { D objd(5); }
No-argument constructor of the base class B
one argument constructor of the derived class D

(PN) (MCA)(2010-11/ EVEN) (2010-13)


256

Constructors in base and derived class without default


constructor

 The compiler looks for the no-argument constructor by default


in the base class

 If there is a constructor in the base class, the following


condition must be met:

 The base class must have a no-argument constructor

 If the base class does not have a default constructor and has
an argument constructor, they must be explicitly invoked,
otherwise the compiler generates error

(PN) (MCA)(2010-11/ EVEN) (2010-13)


257

class B {
public:
B(int a){cout<“one argument constructor of the base class B ”; }
};
class D: public B {
public:
D(int a){cout<“one argument constructor of the derived class D ”;}
};
void main() { D objd(5); }
cannot find ‘default’ constructor to initialize base class ‘B’

(PN) (MCA)(2010-11/ EVEN) (2010-13)


258
Initialisation list

Explicit invocation in the absence of default constructor

class B {
public:
B(int a){cout<“one argument constructor of the base class B ”; }
};
class D: public B {
public:
D(int a): B(a){cout<“one arg constructor of the derived class D ”;}
};
void main() { D objd(5); }
one argument constructor of the base class B
one argument constructor of the derived class D

(PN) (MCA)(2010-11/ EVEN) (2010-13)


class alpha {
259
protected: int a;
public:
alpha(int a1){ cout<<"alpha class constructor called";a=a1;}
~alpha() {cout<<"alpha class destructor called";}
};
class beta:public alpha {
protected: int b;
public: alpa
beta(int a1,int b1):b(b1),alpha(a1) {
cout<<"beta class constructor called“;} beta
~beta() {cout<<"beta class destructor called"; }
}; gama
class gama:public beta {
int c; public:
gama(int a1,int b1,int c1):c(c1),beta(a1,b1) {
cout<<"gama class constructor called“ ; }
~gama() { cout<<"gama class destructor called"; }
void showabc() {cout<<"a is "<<a<<"b is "<<b<<"c is”<<c; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


260

void main() {
gama g1(1,2,3); g1.showabc();
}
alpha class constructor called
beta class constructor called
gama class constructor called
a is 1
b is 2
c is 3
gama class destructor called
beta class destructor called
alpha class destructor called

(PN) (MCA)(2010-11/ EVEN) (2010-13)


261

Constructor in a multiple inherited class invoking default one


class B1 {
Public:
B1() {cout<<“No-argument constructor of the base class B1”; }
};
class B2 {
Public:
B2() {cout<<“No-argument constructor of the base class B2”; }
};
class D: public B2,public B1
{
Public:
D() {cout<<“No-argument constructor of the derived class D ”; }
};
void main() { D objd; }
No-argument constructor of the base class B2
No-argument constructor of the base class B1
No-argument constructor of the derived class D

(PN) (MCA)(2010-11/ EVEN) (2010-13)


262
Constructor in a multiple inherited class with invoking
explicitly
class B1 {
Public:
B1() {cout<<“No-argument constructor of the base class B1”; }
};
class B2 {
Public:
B2() {cout<<“No-argument constructor of the base class B2”; }
};
class D: public B1,public B2
{
Public:
D():B2(),B1() {cout<<“No-arg constructor of the derived class D”; }
};
void main() { D objd; }

No-argument constructor of the base class B1


No-argument constructor of the base class B2
No-argument constructor of the derived class D

(PN) (MCA)(2010-11/ EVEN) (2010-13)


263
Constructor in base and derived classes in multiple
inheritance
class B1 {
Public:
B1() {cout<<“No-argument constructor of the base class B1”; }
};
class B2 {
Public:
B2() {cout<<“No-argument constructor of the base class B2”; }
};
class D: public B1,virtual private B2
{
Public:
D():B1(),B2() {cout<<“No-argument constructor of the derived class D ”; }
};
void main() { D objd; }
No-argument constructor of the base class B2
No-argument constructor of the base class B1
No-argument constructor of the derived class D

(PN) (MCA)(2010-11/ EVEN) (2010-13)


264
Constructor in multilevel inheritance
class B {
public:
B(){
cout<“no argument constructor of the base class B ”; }
};
class D1: public B {
public:
D1(){
cout<“no argument constructor of base class D1 ”; }
};
class D2: public D1 {
public:
D2(){
cout<“no argument constructor of derived class D2 ”; }
};

void main() { D2 objd; }


no argument constructor of the base class B
no argument constructor of base class D1
no argument constructor of derived class D2

(PN) (MCA)(2010-11/ EVEN) (2010-13)


265
Order of invocation of constructors
Method of Inheritance Order of Execution
class D : public B B ( ): base constructor
{… D ( ): derived constructor
};
class D : public B1, public B2 B1 ( ): base constructor
{… B2 ( ): base constructor
}; D ( ): derived constructor
class D:public B1,virtual public B2 B2( ): virtual base constructor
{… B1( ): base constructor
}; D( ): derived constructor
class D1 : public B B ( ): super base constructor
{… D1 ( ): base constructor
}; D2 ( ): derived constructor
class D 2: public D1
{……..
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Destructor in Derived Classes 266
class B1 {
public:
B1(){cout<“no argument constructor of the base class B1 ”; }
~B1(){ cout<“destructor in the base class B1 ”; }
};
class B2 {
public:
B2(){cout<“no argument constructor of the base class B2 ”; }
~B2(){ cout<“destructor in the base class B2 ”; }
};
class D: public B1,public B2 {
public:
D(){cout<“no argument constructor of derived class D ”; }
~D(){ cout<“destructor in the base class D ”; }
};
void main() { D objd; }
no argument constructor of the base class B1
no argument constructor of base class B2
no argument constructor of derived class D
Destructor in the base class D
Destructor in the base class B2
Destructor in the base class B1

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Employee 267
Single Inheritance

class Manager : public Employee {


Manager
const int size= 50; char branch[size];
class Employee { unsigned long div_code;
char ename[size]; public:
unsigned long enumber;
void getdata() {
public:
void getdata() {
Employee::getdata();
cout<<" Enter name :"; cout<<"Enter Branch Name :";
cin>>ename; cin>>branch;
cout<<" Enter Employee no :"; cout<<"Enter Division Code";
cin>>enumber; }
cin>>div_code; }
void putdata() {
cout<<"Name:"<<ename; void putdata() {
cout<<"EmployeeNumber:“ Employee::putdata();
<<enumber; } cout<<Branch Name :"<<branch;
};
cout<<"DivisionCode<<div_code;}
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


268
Enter employee data:
Enter name :Raja
void main() { Enter Employee no :1000
Employee e1; Manager m1 Enter Manager data:
cout<<"Enter employee data:"; Enter name :Vikas
e1.getdata(); Enter Employee no :2000
cout<<"Enter Manager data:"; Enter Branch Name :Bangalore
m1.getdata(); Enter Division Code :1256
cout<<"\n Employee data:"; Employee data:
e1.putdata(); Name: Raja
cout<<"\n Manager data: \n"; Employee Number:1000
m1.putdata(); Manager data:
} Name: Vikas
Employee Number:2000
Branch Name :Bangalore
Division Code :1256

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Person
269

Multilevel Inheritance
Student

class person { Test


protected: class student:protected person
char name[20],sex; int age; {
Result
public: protected: int rollno;
void readdata() { char branch[20];
public:
cin>>name>>sex>>age;
void readdata() {
}
person::readdata();
void showdata() {
cin>>rollno>>branch; }
cout<<" name is "<<name;
void showdata() {
cout<<" sex is "<<sex; person::showdata();
cout<<" age is "<<age; cout<<" rollno:"<<rollno;
} cout<<" branch :"<<branch;
}; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


270

class test:protected student {


protected:
int mark1,mark2,mark3;
public:
void readdata() {
class result:protected test
student::readdata(); {
cin>>mark1>>mark2>>mark3; protected: int total;
}
public:
void showdata() {
student::showdata();
void processmark() {
cout<<"mark1 is :"<<mark1; test::readdata();
cout<<"mark2 is :"<<mark2; total=mark1+mark2+mark3;
cout<<"mark3 is :"<<mark3;
test::showdata();
}};
cout<<"\n total is "<<total;
}
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


271

void main() {
result r1;r1.processmark(); name is raja
} sex is m
age is 21
enter name :raja rollno:25
enter sex :m branch :mca
enter age :21 mark1 is :50
enter rollno :25 mark2 is :60
enter branch :mca mark3 is :70
enter sub1 mark :50 total is 180
enter sub2 mark :60
enter sub3 mark :70

(PN) (MCA)(2010-11/ EVEN) (2010-13)


272

Father Mother
Multiple Inheritance

Child

class father {
float salary;
public:
void assign_salary(float sal) { salary=sal; }
float get_salary() { return salary; }
};
class mother {
float salary;
public:
void assign_salary(float sal) { salary=sal; }
float get_salary() {return salary; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


class child : public father,public mother {
273
float annual_savings,annual_expense,total_revenue;
public: child() {}
float saving_expenditure() {
annual_expense=father::get_salary();
annual_savings=mother::get_salary();
total_revenue=annual_savings+annual_expense;
return total_revenue; } };
void main() {
child c1;
c1.father::assign_salary(300000);
c1.mother::assign_salary(200000);
cout<<"father salary:"<<c1.father::get_salary();
cout<<"mother salary:"<<c1.mother::get_salary();
cout<<"total annual revenue is Rs."<<
c1.saving_expenditure(); }
father salary:300000
mother salary:200000
total annual revenue is Rs.500000

(PN) (MCA)(2010-11/ EVEN) (2010-13)


274

Ambiguity Resolution in Inheritance – Single Level

class a {
int x;
public:
void get_x(int x1) {x=x1; }
void main() {
void show() {
b b1;
cout<<“\n x="<<x; }
b1.get_x(100);
};
b1.get_y(200);
class b:public a {
b1.show();
int y;
public :
b1.show();
void get_y(int y1) {y=y1;} }
void show() {
cout<<“\n y="<<y; } y=200
}; y=200

(PN) (MCA)(2010-11/ EVEN) (2010-13)


275

class a {
int x;
public: void main() {
void get_x(int x1) {x=x1; } b b1;
void show() { b1.get_x(100);
cout<<“\n x="<<x; } b1.get_y(200);
}; b1.show();
class b:public a { }
int y;
public : x=100
void get_y(int y1) {y=y1;} y=200
void show() {
a::show();
cout<<“\n y="<<y; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


276

class a {
int x;
void main() {
public: b b1;
void get_x(int x1) {x=x1; } b1.get_x(100);
void show() { b1.get_y(200);
cout<<“\n x="<<x; } b1.a::show();
};
b1.b::show();
class b:public a {
}
int y;
public : x=100
void get_y(int y1) {y=y1;} y=200
void show() {
cout<<“\n y="<<y; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


277

Ambiguity Resolution in Inheritance – Multiple


class a { class c: public a,b {
public: public:
void show() { void show() {
cout<<" this is show from a a::show(); b::show();
class"; } cout<<" this is show from c
}; class \n"; }
};

class b {
void main() {
public:
c c1; c1.show(); }
void show() {
cout<<" this is show from b this is show from a class
class”; }
this is show from b class
}; this is show from c class

(PN) (MCA)(2010-11/ EVEN) (2010-13)


278

Ambiguity Resolution in Inheritance – Multiple


class a { class c: public a, public b {
public: public:
void show() { void show() {
cout<<" this is show from a cout<<" this is show from c
class"; } class \n"; }
}; };

void main() {
class b {
c c1; c1.a::show();
public:
c1.b::show(); c1.show();
void show() {
}
cout<<" this is show from b this is show from a class
class”; }
this is show from b class
}; this is show from c class

(PN) (MCA)(2010-11/ EVEN) (2010-13)


279

Ambiguity Resolution in Inheritance – Multiple


class a { class c: public a, public b {
}; public:
void show() {
class b { cout<<" this is show from c
}; class \n"; }
};

void main() {
c c1; c1.show();
}
this is show from c class

(PN) (MCA)(2010-11/ EVEN) (2010-13)


280

Ambiguity Resolution in Inheritance – Multiple


class a { class c: public a, public b {
public: };
void show() {
cout<<" this is show from a void main() {
class \n"; } c c1; c1.show();
}; }
this is show from a class
class b {
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


281

Ambiguity Resolution in Inheritance – Multiple


class a { class c: public a, public b {
public: };
void show() {
cout<<" this is show from a class
void main() {
"; }
};
c c1; c1.show();
}
class b {
public: Member is ambiguous:
void show() { 'a::show' and 'b::show'
cout<<" this is show from b class
“; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


282

Multipath Inheritance and Virtual base classes

Parent

Child1 Child2

Grandchild

(PN) (MCA)(2010-11/ EVEN) (2010-13)


283

class parent {
protected : int basedata;
public: void main() {
void initdata(int x) {basedata=x;} grandchild g;
}; g.initdata(100); //Error
class child1: public parent { cout<<g.getdata();
}; }
class child2: public parent {
};
class grandchild: public child1,public child2 {
public:
int getdata() { Member is ambiguous:
return basedata; //Error 'parent::basedata' and
} 'parent::basedata'
}; Member is ambiguous:
'parent::initdata' and
'parent::initdata

(PN) (MCA)(2010-11/ EVEN) (2010-13)


284

class parent {
protected : int basedata; void main() {
public: grandchild g;
void initdata(int x) { g.initdata(100);
basedata=x; }
cout<<g.getdata();
};
class child1: virtual public parent { //share }
copy of parent};
class child2: public virtual parent { //share
copy of parent};
class grandchild: public child1,public child2 { 100
public:
int getdata() { return basedata;
// O.K: only one copy of parent} Note: Friendship is not
};
inheritive, transitive and
mutual

(PN) (MCA)(2010-11/ EVEN) (2010-13)


285

Virtual Functions

 One of the most powerful feature of C++ is that it allows


objects of different types to respond differently to the same
function call

Ex: move message in person class and polygon class


draw message in circle class and rectangle class
stop method in car class and airplane class

 This is called polymorphism and is achieved by many ways


such as function overloading, operator overloading and virtual
functions

(PN) (MCA)(2010-11/ EVEN) (2010-13)


286

Polymorphism

Compile Time Run Time

Function Overloading Operator Overloading Virtual Functions

(PN) (MCA)(2010-11/ EVEN) (2010-13)


287

Compile Time Polymorphism – Function Overloading

//Declarations
int add(int a, int b); //prototype 1
int add(int a, int b ,int c); //prototype 2
double add(double x, double y); //prototype 3
double add(int p,double q); //prototype 4
double add(double p, int q); //prototype 5

//Function calls
cout<<add (5,10); //uses prototype 1
cout<<add (15,10.0); //uses prototype 4
cout<<add (12.5,7.5); //uses prototype 3
cout<<add (5,10,15); //uses prototype 2
cout<<add (0.75,5); //uses prototype 5

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Rice Flour 288
Back

 Run Time Polymorphism is achieved by means of virtual


functions
 Run Time Polymorphism is rendered possible by the fact that a
pointer to a base class may also point to sub class

class X { void main() {


// …. X *p; // p is a pointer to object of base class
} Y y;
class Y : public X { p=&y; // p can also point to object of sub class
//…. }
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


289
Base
class Base {
public:
void show() { Derv1 Derv2
cout<<“\n Base"; }
};
class Derv1: public Base {
void main() {
public: Derv1 dv1;
void show() { Derv2 dv2;
cout<<“\n Derv1"; }
};
Base *ptr;
class Derv2: public Base { ptr=&dv1;
public:
ptr->show(); ptr=&dv2;
void show() {
cout<<“\n Derv2"; } ptr->show();
}; }

Base
Base

(PN) (MCA)(2010-11/ EVEN) (2010-13)


As you can see, the function in the base class is always 290
executed. The compiler ignores the contents of the pointer ptr
and chooses the member function that matches the type of the
pointer.
Base
ptr Show()
&Derv1

ptr->show()
Derv1
ptr Show()

&Derv2

ptr->show()
Derv2
Show()

Static Binding

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Virtual Member Functions Accessed with Pointers 291

class Base {
public:
virtual void show() { void main() {
cout<<“\n Base"; } Derv1 dv1;
}; Derv2 dv2;
class Derv1: public Base { Base *ptr;
public: ptr=&dv1;
void show() {
ptr->show();
cout<<“\n Derv1"; }
ptr=&dv2;
};
class Derv2: public Base {
ptr->show();
public: }
void show() { Derv1
cout<<“\n Derv2"; } Derv2
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


292

Base
ptr Show()
&Derv1

ptr->show()
Derv1
ptr Show()

&Derv2

ptr->show()
Derv2
Show()

Dynamic Binding

(PN) (MCA)(2010-11/ EVEN) (2010-13)


293
How Dynamic Binding Achieved????????

 Now, as you can see, the member function of the derived classes,
not the base class are executed

 We change the contents of ptr from the address of Derv1 to that of


Derv2, and the particular instance of show() that is executed also
changes

 So the same function call ptr->show(); exectues different


functions, depending on the contents of ptr

 The rule is that the compiler selects the function based on the
contents of the pointer ptr, not on the type of the pointer, as in the
earlier program

Note: In general, a member function should be declared as virtual


whenever if it is anticipated that at least some of its subclasses
will define their own local version of the function

(PN) (MCA)(2010-11/ EVEN) (2010-13)


294
Type Casting on Base and Derived class pointers

void main() {
x X; y Y; x *p;
class x { p=&X;
public: p->f();
void f() { p=&Y;
cout<<"\n this is x::f() of x class";} ((y*)p)->f();
void f1() { y *p1;
cout<<"\n x::f1()exeucting"; } p1->f1();
}; ((x*)p1)->f1();
class y:public x { }
public: this is x::f() of x class
void f() { this is y::f() of y class
cout<<"this is y::f() of y class";} y::f1()exeucting
void f1() { x::f1()exeucting
cout<<"\n y::f1()exeucting"; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


295
V
Array of Base Pointers (Hierarchial Inheritance) B T C A
class vehicle { public: virtual void stop() {
cout<<"i am vehicle, i don't have any specific stop method";} };
class bicycle:public vehicle {
public: void stop() {
cout<<"i am bicycle , use very ordinary breaking system"; } };
class twowheeler:public vehicle {
public: void stop() {
cout<<"i am bajaj discover, use disc break system"; } };
class car:public vehicle {
public: void stop() {
cout<<"i am ford car , use antilock breaking system"; } };
class aeroplane:public vehicle {
public: void stop() {
cout<<"i am Boeing US742 , use hydraulic/pneaumatic breaking system";}};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


296

void main() { switch(choice){


vehicle vh; bicycle hero; case 0:ptr[choice]->stop();
twowheeler bajaj; break;
car ford; aeroplane boeing; case 1:
int choice; ptr[choice]->stop(); break;
vehicle *ptr[]={&vh,&hero, case 2:
&bajaj,&ford,&boeing}; ptr[choice]->stop(); break;
cout<<"stop method you prefer :"; case 3:
cout<<"0. Vehicle 1. Bicycle 2. ptr[choice]->stop(); break;
TwoWheeler 3. Car case 4:
4. Aeroplane 5. Exit"; ptr[choice]->stop(); break;
do { case 5: exit(1); }
cout<<"enter your choice :"; }while(choice!=5);
cin>>choice; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Stop method you prefer :
297
0. Vehicle
1. Bicycle
2. TwoWheeler
3. Car Array of Derived Pointers??????????
4. Aeroplane
5. Exit
enter your choice :0
i am vehicle, i don't have any specific stop method
enter your choice :1
i am bicycle , use very ordinary breaking system
enter your choice :2
i am bajaj discover, use disc break system
enter your choice :3
i am ford car , use antilock breaking system
enter your choice :4
i am Boeing US742,use hydraulic/pneaumatic breaking system
enter your choice :5

(PN) (MCA)(2010-11/ EVEN) (2010-13)


298
Derived Pointers (Multilevel Inheritance)

class vehicle { public: void stop() {


cout<<"i am vehicle, i don't have any specific stop method";} };
class bicycle:public vehicle {
public: void stop() {
cout<<"i am bicycle , use very ordinary breaking system"; } };
class twowheeler:public bicycle {
public: void stop() {
cout<<"i am bajaj discover, use disc break system"; } };
class car:public twowheeler {
public: void stop() {
cout<<"i am ford car , use antilock breaking system"; } };
class aeroplane:public car {
public: void stop() {
cout<<"i am Boeing US742 , use hydraulic/pneaumatic breaking system";}};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


299
void main() switch(choice) {
{ case 0:
((vehicle*)ptr)->stop(); break;
int choice;
case 1:
aeroplane *ptr; ((bicycle*)ptr)->stop(); break;
cout<<" \n stop method you case 2:
prefer :"; ((twowheeler*)ptr)->stop(); break;
case 3:
cout<<"\n 0. Vehicle \n 1. ((car*)ptr)->stop(); break;
Bicycle \n 2. case 4:
TwoWheeler \n 3. Car \n ((aeroplane*)ptr)->stop(); break;
4. Aeroplane\n 5. Exit\n"; case 5:
do exit(1);
}
{ }while(choice!=5);
cout<<"\n enter your }
choice :";
cin>>choice;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


300

Array of Base Pointers (Multilevel Inheritance)

class vehicle { public: virtual void stop() {


cout<<"i am vehicle, i don't have any specific stop method";} };
class bicycle:public vehicle {
public: void stop() {
cout<<"i am bicycle , use very ordinary breaking system"; } };
class twowheeler:public bicycle {
public: void stop() {
cout<<"i am bajaj discover, use disc break system"; } };
class car:public twowheeler {
public: void stop() {
cout<<"i am ford car , use antilock breaking system"; } };
class aeroplane:public car {
public: void stop() {
cout<<"i am Boeing US742 , use hydraulic/pneaumatic breaking system";}};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


301

void main() { switch(choice){


vehicle vh; bicycle hero; case 0:ptr[choice]->stop();
twowheeler bajaj; break;
car ford; aeroplane boeing; case 1:
int choice; ptr[choice]->stop(); break;
vehicle *ptr[]={&vh,&hero, case 2:
&bajaj,&ford,&boeing}; ptr[choice]->stop(); break;
cout<<"stop method you prefer :"; case 3:
cout<<"0. Vehicle 1. Bicycle 2. ptr[choice]->stop(); break;
TwoWheeler 3. Car case 4:
4. Aeroplane 5. Exit"; ptr[choice]->stop(); break;
do { case 5: exit(1); }
cout<<"enter your choice :"; }while(choice!=5);
cin>>choice; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


302
Array of derived pointers

class vehicle { public: void stop() {


cout<<"i am vehicle, i don't have any specific stop method";} };
class bicycle:public vehicle {
public: void stop() {
cout<<"i am bicycle , use very ordinary breaking system"; } };
class twowheeler:public bicycle {
public: void stop() {
cout<<"i am bajaj discover, use disc break system"; } };
class car:public twowheeler {
public: void stop() {
cout<<"i am ford car , use antilock breaking system"; } };
class aeroplane:public car {
public: void stop() {
cout<<"i am Boeing US742 , use hydraulic/pneaumatic breaking
system";}};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


303
void main()
switch(choice) {
{
case 0:
int choice;
((vehicle*)ptr[0])->stop(); break;
vehicle v; bicycle b;
case 1:
twowheeler t;
((bicycle*)ptr[1])->stop(); break;
car c; aeroplane a;
case 2:
aeroplane *ptr[]={(aeroplane
*)&v, (aeroplane *)&b, ((twowheeler*)ptr[2])->stop();
aeroplane *)&t, (aeroplane break;
*)&c,&a}; case 3:
cout<<" \n stop method you ((car*)ptr[3])->stop(); break;
prefer :"; case 4:
cout<<"\n 0. Vehicle \n 1. ((aeroplane*)ptr[4])->stop();
Bicycle \n 2. TwoWheeler \n 3. break;
Car \n 4. Aeroplane\n 5. case 5:
Exit\n";
exit(1);
do
}
{
}while(choice!=5);
cout<<"\n enter your choice :";
}
cin>>choice;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


304

Stop method you prefer :


0. Vehicle
1. Bicycle
2. TwoWheeler
3. Car
4. Aeroplane
5. Exit
enter your choice :0
i am vehicle, i don't have any specific stop method
enter your choice :1
i am bicycle , use very ordinary breaking system
enter your choice :2
i am bajaj discover, use disc break system
enter your choice :3
i am ford car , use antilock breaking system
enter your choice :4
i am Boeing US742,use hydraulic/pneaumatic breaking
system
enter your choice :5

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Pure Virtual Function 305

 Virtual functions defined inside the base class normally serve as a framework
for future design of the class hierarchy
 These functions can be overridden by the methods in the derived classes
 In most of these cases, these virtual functions are defined with a null body; it
has no definition
 Such functions in the base class are similar to do-nothing or dummy and in C+
+, they are called pure virtual functions
syntax of pure virtual function
class myclass
{
public
………
virtual ReturnType FunctionName(arguments)=0;
……..
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


306

 A pure virtual function in an unfinished placeholder that


the derived class is expected to complete; the following
are the properties of pure virtual functions
 A pure virtual function has no implementation in the
base class hence, a class with pure virtual function
cannot be instantiated
 It act as an empty bucket (virtual function is a partially
filled bucket) that the derived class supposed to fill
 A pure virtual member function can be invoked by its
derived class
 A class with one or more pure virtual functions cannot
be instantiated and this class is called abstract class

(PN) (MCA)(2010-11/ EVEN) (2010-13)


307
V
Array of Base Pointers (Hierarchial Inheritance) B T C A

class vehicle { public: virtual void stop()=0;};


class bicycle:public vehicle {
public: void stop() {
cout<<"i am bicycle , use very ordinary breaking system"; } };
class twowheeler:public vehicle {
public: void stop() {
cout<<"i am bajaj discover, use disc break system"; } };
class car:public vehicle {
public: void stop() {
cout<<"i am ford car , use antilock breaking system"; } };
class aeroplane:public vehicle {
public: void stop() {
cout<<"i am Boeing US742 , use hydraulic/pneaumatic breaking
system";}};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


308

void main() { switch(choice){


bicycle hero; case 0:ptr[choice]->stop();
twowheeler bajaj; break;
car ford; aeroplane boeing; case 1:
int choice; ptr[choice]->stop(); break;
vehicle *ptr[]={&hero, case 2:
&bajaj,&ford,&boeing}; ptr[choice]->stop(); break;
cout<<"stop method you prefer :"; case 3:
cout<<“0. Bicycle 1. ptr[choice]->stop(); break;
TwoWheeler 2. Car case 4: exit(1); }
3. Aeroplane 4. Exit"; }while(choice!=5);
do { }
cout<<"enter your choice :";
cin>>choice;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


309
Stop method you prefer :
0. Bicycle
1. TwoWheeler
2. Car
3. Aeroplane
4. Exit
enter your choice :0
i am bicycle , use very ordinary breaking system
enter your choice :1
i am bajaj discover, use disc break system
enter your choice :2
i am ford car , use antilock breaking system
enter your choice :3
i am Boeing US742,use hydraulic/pneaumatic breaking system
enter your choice :4

(PN) (MCA)(2010-11/ EVEN) (2010-13)


310

Virtual Destructors

 Just like declaring member functions as virtual,


destructors can be declared as virtual, whereas
constructors cannot be virtual

 Virtual destructors are controlled in the same way as


virtual functions

 When a derived object pointed by the base class pointer


is deleted, destructor of the derived class as well as
destructors of all its base classes are invoked

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Father 311

class father {
protected: char *fname; Son
public:
father(char *fn) {
fname=new char[strlen(fn)+1]; strcpy(fname,fn); }
virtual ~father(){delete fname;cout<<"~father() is invoked"; }
virtual void show() {cout<<"father name:"<<fname; }
};
class son:public father {
protected: char *sname;
public:
son(char *fn,char *sn):father(fn) {
sname=new char [strlen(sn)+1];strcpy(sname,sn); }
~son() {delete sname; cout<<"~son() is invoked"; }
void show(){cout<<"father name:"<<fname<<"son
name:"<<sname; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


void main() {
father *basep; 312
basep=new father("Rumesh");
cout<<"\n basep points to base object";
basep->show(); delete basep;
basep=new son("Rumesh","S.Tendulkar");
cout<<"basep points to derived object";
basep->show(); delete basep;
}
basep points to base object
father name:Rumesh
~father() is invoked
basep points to derived object
father name:Rumesh
son name:S.Tendulkar
~son() is invoked
~father() is invoked

In the above program, if the destructor is made as non-virtual


destructor in the base class, only the base class destructor is
invoked when the derived reference is deleted.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


313
Run Time Templates

 Template support generic programming that allows to develop


reusable software components such as functions and classes which
handle different data types in a single framework

 A significant benefit of template is reusability of source code that


eliminates redundant coding

 For instance, operations such as sort, search, swap, etc., which


support various data types can be developed as a template; whereas a
normal function is normally designed to handle a specific data type

 The templates declared for functions are called function and classes
are called class template respectively

 They perform respective operations depending on the data type of the


arguments passed to them

(PN) (MCA)(2010-11/ EVEN) (2010-13)


314

Function Templates or Generic Function

 A function template is used to create a pattern that


describes what a function will do, leaving the compiler
to fill in the details as needed

 The general format of a template function definition is


shown below:

template <class Ttype> ret-type func-name (arg- list)


{
// body of the function
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


315

 For example, a function template is shown in the following


slide for swapping integer, character, and float data type
whose logic of swapping is same and differs only in terms of
data-type

Function Non-Overloading & Function overloading

(PN) (MCA)(2010-11/ EVEN) (2010-13)


316

// This is a function template which works by reference


template <class X>
void swapargs (X &a, X &b) {
X temp; temp = a; a = b; b = temp; }

void main() {
int i=10, j=20; double x=10.1, y=23.3; char a='x', b='z';
cout << "Original i, j: " << i << ' ' << j ;
cout << "Original x, y: " << x << ' ' <<y;
cout << "Original a, b: " << a << ' ' << b;
swapargs(i,j); // swap integers
swapargs(x,y); // swap floats
swapargs(a,b); // swap chars
cout << "Swapped i, j: " << i << ' ' << j ;
cout << "Swapped x, y: " << x << ' ' << y;
cout << "Swapped a, b: " << a << ' ' << b;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


317

Original i, j: 10 20
Original x, y: 10.1 23.3
Original a, b: x z

Swapped i, j: 20 10
Swapped x, y: 23.3 10.1
Swapped a, b: z x

(PN) (MCA)(2010-11/ EVEN) (2010-13)


318

Function template in finding maximum of two data items

// This is a function template which works by value


template <class T> T max(T a, T b)
{ return a>b ?a : b; }
void main() {
char ch1,ch2; int i, j; float m, n;
cout<<"enter two ch aracters :"; cin>>ch1>>ch2;
cout<<"enter two integer number :"; cin>>i>>j;
cout<<"enter two float numbers :"; cin>>m>>n;
cout<<“The maximum of "<<ch1<<" ,"<<ch2<<"is"<<max(ch1,ch2);
cout<<“The maximum of "<<i<<" ,"<<j<<" is "<<max(i,j);
cout<<“The maximum of "<<m<<" ,"<<n<<" is "<<max(m,n);
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


319

enter two characters : a b


enter two integer number : 5 7
enter two float numbers : 34.5 56.8

The maximum of a ,b is b
The maximum of 5 ,7 is 7
The maximum of 34.5 ,56.8 is 56.8

(PN) (MCA)(2010-11/ EVEN) (2010-13)


320

Function and Function Template

 Function template is not suitable for handling all data types


and hence, it is necessary to override function templates by
using normal functions for specific data types

 For example, when a statement such as, max(String1, String2)


is given to the template declared in the earlier program for
finding maximum of String1 and String2, then it will not
produce the desired result

 Even though the concept is same in finding maximum one over


other, the definition for comparing strings is different from
comparing integer, character or floating point type

(PN) (MCA)(2010-11/ EVEN) (2010-13)


321

It requires the function having the following definition.

char *max( char *a, char *b)


{
if( strcmp( a, b) > 0 ?a : b);
}

If the program has both function and function template with the
same name, first the compiler selects the normal function, scans
for the match with the requested datatype, otherwise, it creates
a function using a function template

(PN) (MCA)(2010-11/ EVEN) (2010-13)


322

template <class T> T max(T a, T b) {return a>b?a:b; }


char* max(char *a, char *b) { return strcmp(a,b)>0?a:b; }
void main() {
char ch1,ch2; char str1[20],str2[20]; int i,j; float m,n;
cout<<"enter two characters :"; cin>>ch1>>ch2;
cout<<"enter two integer number :"; cin>>i>>j;
cout<<"enter two float numbers :"; cin>>m>>n;
cout<<"enter two string :"; cin>>str1>>str2;
cout<<"the max of "<<ch1<<" ,"<<ch2<<" is“<<max(ch1,ch2);
cout<<"the max of "<<i<<" ,"<<j<<" is"<<max(i,j);
cout<<"the max of "<<m<<" ,"<<n<<" is"<<max(m,n);
cout<<"the max of "<<str1<<" ,"<<str2<<" is"<<max(str1,str2);
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


323

enter two characters : a b


enter two integer number : 23 45
enter two float numbers : 34.5 6.8
enter two string : india china
the max of a ,b is b
the max of 23 ,45 is 45
the max of 34.5 ,6.8 is 34.5
the max of india ,china is india

(PN) (MCA)(2010-11/ EVEN) (2010-13)


324

Overloaded Function Templates

 The function templates can also be overloaded with


multiple declarations; it may be overloaded by (other)
functions of its name or by (other) template functions
of the same name

 Overloaded function template must differ either in


terms of numbers of parameters or their type similar to
function overloading

(PN) (MCA)(2010-11/ EVEN) (2010-13)


325

template <class T > void display(T data)


{ cout<<data; } // single template argument
template<class T> void display(T data, int count)
{
for(int i=0;i<count;i++)//template and standard argument
cout<<data; }
void main() {
display(5); // invoke single template argument
display(8.5); // invoke single template argument
display(100,4); // invoke template & standard argument
display(“Good Morning”,3);//invoke template & standard argument
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


326

5
8.5
100
100
100
100
Good Morning
Good Morning
Good Morning

(PN) (MCA)(2010-11/ EVEN) (2010-13)


327
Overloaded Function and Overloaded Function Templates
template <class T> T max(T a, T b) { return a>b?a:b; }

template <class T> T max(T a, T b, T c){


return a>b?a>c?a:c:b>c?b:c; }

char* max(char *a, char *b) { return strcmp(a,b)>0?a:b; }

char* max(char *a, char *b, char *c) {


return strcmp(a,b)>0?strcmp(a,c)>0?a:c:strcmp(b,c)>0?b:c; }
void main() {
char ch1,ch2,ch3; char str1[20],str2[20],str3[20]; int i,j; float m,n;
cout<<"enter three characters :"; cin>>ch1>>ch2>>ch3;
cout<<"enter two integer number :"; cin>>i>>j;
cout<<"enter two float numbers :"; cin>>m>>n;
cout<<"enter three string :"; cin>>str1>>str2>>str3;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


328

cout<<"the maximum of "<<ch1<<" ,"<<ch2<<" is ";


cout<<max(ch1,ch2);// invoke two argument template max
cout<<"the maximum of "<<i<<" ,"<<j<<" is ";
cout<<max(i,j);// invoke two argument template max
cout<<"the maximum of "<<m<<" ,"<<n<<" is ";
cout<<max(m,n);// invoke two argument template max
cout<<"the maximum of "<<str1<<" ,"<<str2<<" is ";
cout<<max(str1,str2);// invoke two argument function max
cout<<"the maximum of "<<ch1<<" ,"<<ch2<<" ,"<<ch3<<"is";
cout<<max(ch1,ch2,ch3);// invoke three argument template max
cout<<"the maximum of "<<str1<<" ,"<<str2<<" ,"<<str3<<"is";
cout<<max(str1,str2,str3);// invoke three argument function max
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


329

enter three characters :a b c


enter two integer number :4 5
enter two float numbers :6.7 8.9
enter three string :mala kala rama

the maximum of a ,b is b
the maximum of 4 ,5 is 5
the maximum of 6.7 ,8.9 is 8.9
the maximum of mala ,kala is mala
the maximum of a ,b ,c is c
the maximum of mala ,kala ,rama is rama

(PN) (MCA)(2010-11/ EVEN) (2010-13)


330

Multiple Argument Function Template

 In all the function template we have come across dealt with a


single generic argument

 Declarations of a function template for functions having


multiple parameters of different types requires multiple
generic arguments

(PN) (MCA)(2010-11/ EVEN) (2010-13)


331

struct A {int x; int y; };


void main() {
struct B {int x; double y; };
A S1; B S2;
Assign_A( 5 ,10 ,S1);
template <class T>
Assign_B(15,3.1415,S2);
void Assign_A( T a, T b, A&S1) cout<<"S1.x : "<<S1.x<<endl;
{ S1.x = a; S1.y = b; } cout<<"S1.y : "<<S1.y<<endl;
cout<<"S2.x : "<<S2.x<<endl;
template <class T, class U> cout<<"S2.y : "<<S2.y<<endl;
void Assign_B( T a, U b, B &S2) }
{ S2.x = a; S2.y = b; } S1.x : 5
S1.y : 10
S2.x : 15
S2.y : 3.1415

(PN) (MCA)(2010-11/ EVEN) (2010-13)


332

Multiple Argument Function Template

template <class T> T max(T a, T b) { return a>b?a:b; }


template <class T, class V> V max(T a, V b) { return a>b?a:b; }
template <class T> T max(T a, T b, T c)
{ return a>b?a>c?a:c:b>c?b:c; }
char* max(char *a, char *b) { return strcmp(a,b)>0?a:b; }
char* max(char *a, char *b, char *c)
{return strcmp(a,b)>0?strcmp(a,c)>0?a:c:strcmp(b,c)>0?b:c;}
void main() {
char ch1,ch2,ch3; char str1[20],str2[20],str3[20]; int i,j; float m,n;
cout<<"enter three characters :"; cin>>ch1>>ch2>>ch3;
cout<<"enter two integer number :"; cin>>i>>j;
cout<<"enter two float numbers :"; cin>>m>>n;
cout<<"enter three string :"; cin>>str1>>str2>>str3;

(PN) (MCA)(2010-11/ EVEN) (2010-13)


333

cout<<"the maximum of "<<ch1<<" ,"<<ch2<<" is ";


cout<<max(ch1,ch2);// invoke two argument template max
cout<<"the maximum of "<<i<<" ,"<<j<<" is ";
cout<<max(i,j);// invoke two argument template max
cout<<"the maximum of "<<m<<" ,"<<n<<" is ";
cout<<max(m,n);// invoke two argument template max
cout<<"the maximum of "<<str1<<" ,"<<str2<<" is ";
cout<<max(str1,str2);// invoke two argument function max
cout<<"the maximum of "<<ch1<<","<<ch2<<","<<ch3<<"is";
cout<<max(ch1,ch2,ch3);//invoke 3 argument template max
cout<<"the maximum of "<<str1<<" ,"<<str2<<","<<str3<<"is";
cout<<max(str1,str2,str3);//invoke 3 argument function max
cout<<"the maximum of "<<i<<" ,"<<m<<" is ";
cout<<max(i,m)<<endl;// invoke two argument template max
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


334

enter three characters :a b c


enter two integer number :5 8
enter two float numbers :3.5 6.2
enter three string :anbu bala mohan
the maximum of a ,b is b
the maximum of 5 ,8 is 8
the maximum of 3.5 ,6.2 is 6.2
the maximum of anbu ,bala is bala
the maximum of a ,b ,c is c
the maximum of anbu ,bala ,mohan is mohan
the maximum of 5 ,8.5 is 8.5

(PN) (MCA)(2010-11/ EVEN) (2010-13)


335

Class Template or Generic Classes

 In addition to generic functions, it is also possible to


define a generic class
 Create a class that defines all the algorithms used by
that class; however, the actual type of the data being
manipulated will be specified as a parameter when
objects of that class are created
 These classes model a generic class which support
similar operations for different data types
 For example say a generic stack class can be created,
which can be used for storing data of type integer,
float, double, and so on; in turn reduces the resources
in creating a separate class for the above said types

(PN) (MCA)(2010-11/ EVEN) (2010-13)


336

The syntax of declaring class templates


Keyword template data types T1,T2…,

template <class T1, class T2, ……>


class Classname {
Tl data1;
// data items of template type T1,T2,…
………
Void func1 (T1 a, T2 &b)
………
// functions of template arguments T1,T2
T func2 (T2 *x, T2 *y);
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


337

Consider an example of a stack (modeling last-in-first-out data


structure ) to illustrate the need and benefits of class
templates

The class declarations for stacks of type character, integer,


and double would be as follows

(PN) (MCA)(2010-11/ EVEN) (2010-13)


338

const int SIZE = 10;


// This creates the integer type stack class
class intstack {
private: int stck[SIZE]; int tos;
public: intstack( ) { tos=0;} void push(int i); int pop();};
// This creates the double type stack class
class doublestack {
private: double stck[SIZE]; int tos;
public: doublestack() {tos=0;} void push(double i);double pop(); };
// This creates the character type stack class
class charstack {
private: char stck[SIZE]; int tos;
public: charstack( ) { tos=0;} void pushchar c); char pop(); };

(PN) (MCA)(2010-11/ EVEN) (2010-13)


339

Template declaration enables substitution of code for all the


above three declarations of stacks with a single template class
// Create a generic stack class
const int SIZE = 10;
template <class StackType> class stack {
StackType stck[SIZE]; // holds the stack
int tos; // index of top-of-stack
public:
stack() { tos = 0; } // initialize stack
void push(StackType ob); // push object on stack
StackType pop(); // pop object from stack
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


340

Implementation of Stack class using Template class.

// Create a generic stack class


struct student{char name[20],int rollno,int mark1,int mark2;};
const int SIZE = 10;
template <class StackType> class stack {
StackType stck[SIZE]; // holds the stack
int tos; // index of top-of-stack
public:
stack() { tos = 0; } // initialize stack
void push(StackType ob); // push object on stack
StackType pop(); // pop object from stack
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


341

// Push an object.
template<class StackType>void stack<StackType>::push(StackType ob)
{ if(tos==SIZE) { cout << "Stack is full.\n"; return; }
stck[tos] = ob; tos++; }
// Pop an object.
template <class StackType> StackType stack<StackType>::pop() {
if(tos==0) {cout << "Stack is empty.\n"; return 0; }
tos--; return stck[tos]; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


342

void main( ) {
// Demonstrate character stack
stack<char> cs; // create character stack
int i; cs.push('a'); cs.push('b'); cs.push('c');
cout<<"character stack :";
for(i=0; i<3; i++) cout << "Pop character stack : "<< cs.pop();
// demonstrate int stack
stack<int> is; // create integer stack
is.push(1); is.push(2); is.push(3);
cout<<"integer stack :";
for(i=0; i<3; i++) cout <<"Pop integer stack :"<< is.pop();

(PN) (MCA)(2010-11/ EVEN) (2010-13)


343

// demonstrate double stack


stack<double> ds; // create double stack
ds.push(1.1); ds.push(2.2);ds.push(3.3); cout<<"double
stack :";
for(i=0; i<3; i++) cout << "Pop double stack : " << ds.pop();

// demonstrate string stack


stack<char*> ss; // create string stack
ss.push("anbu"); ss.push("bala"); ss.push("chandru");
cout<<"string stack :";
for(i=0; i<3; i++) cout << "Pop string stack : "<< ss.pop();

(PN) (MCA)(2010-11/ EVEN) (2010-13)


344
// demonstrate record stack
stack<student>stc; // create record stack
student st;
student s[3]={{"raja",1,45,50},{"ravi",2,50,80},{"rama",3,60,90}};
for(i=0; i<3; i++)
stc.push(s[i]);
cout<<"\n Record stack \n ";
for(i=0; i<3; i++) {
st=stc.pop();
cout<<"\n Pop Record Stack"<<i<<" ";
cout <<st.name<<" ";
cout <<st.rollno<<" ";
cout <<st.mark1<<" ";
cout <<st.mark2<<" ";
}
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


345

character stack : string stack :


Pop character stack : c Pop string stack : chandru
Pop character stack : b Pop string stack : bala
Pop character stack : a Pop string stack : anbu

integer stack :
Record stack
Pop integer stack : 3
Pop integer stack : 2 Pop Record Stack0 rama 3 60 90
Pop integer stack : 1 Pop Record Stack1 ravi 2 50 80
Pop Record Stack2 raja 1 45 50
double stack :
Pop double stack : 3.3
Pop double stack : 2.2
Pop double stack : 1.1

(PN) (MCA)(2010-11/ EVEN) (2010-13)


346

Template with more generic data types

 A template class can have more than one generic data type

 To use more than one data type, declare all the data types
required by the class in a comma-separated list within the
template specification class

(PN) (MCA)(2010-11/ EVEN) (2010-13)


347

template <class Type1, class Type2>


class myclass {
Type1 i; Type2 j;
public:
myclass(Type1 a, Type2 b) { i = a; j = b; }
void show() { cout << i << ‘, ' << j << '\n'; }
};
void main() {
myclass <int, double> ob1(10, 0.23);
myclass <char,char*> ob2('X', "Templates help in generic Pgmg.”);
ob1.show(); // show int, double
ob2.show(); // show char, char *
}
10,0.23
X, Templates help in generic pgmg.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


348

C++ I/O System Basics

Overloading << and >>

 The << and >> operators are overloaded in C++ to perform


I/O operations on C++’s built-in types

 In the languages of C++, the << operator is referred to as the


insertion operator because it inserts character into a stream

 Likewise, the >> input operator is called extraction operator


because it extracts characters from a stream

 The function that overload the insertion and extraction


operators are called inserters and extractors respectively

(PN) (MCA)(2010-11/ EVEN) (2010-13)


349

Syntax of Insertion and Extraction

ostream &operator<<(ostream &stream, class_type obj)


{
//body of inserter
return stream;
}

istream &operator>>(istream &stream, class_type &obj)


{
//body of extractor
return stream;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


350

Inserter and Extractor Example:

class phonebook {
public: char name[80]; int areacode; int prefix; int num;
public: phonebook() { };
phonebook(char *n, int a, int p, int nm)
{ strcpy(name, n); areacode = a; prefix = p; num = nm; }
};
// Input name and telephone number.
istream &operator>>(istream &stream, phonebook &o) {
cout << "Enter name: "; stream >> o.name;
cout << "Enter area code: "; stream >> o.areacode;
cout << "Enter prefix: "; stream >> o.prefix;
cout << "Enter number: "; stream >> o.num;
return stream; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


351

// Display name and phone number.


ostream &operator<<(ostream &stream, phonebook o) {
stream << o.name << " ";
stream << "(" << o.areacode << ") ";
stream << o.prefix << "-" << o.num << "\n";
return stream; }

void main() { phonebook a; cin >> a; cout << a; }


Enter name: Raja
Enter area code: 111
Enter Prefix: 555
Enter number: 9991
Raja (111) 555-9991

(PN) (MCA)(2010-11/ EVEN) (2010-13)


352

What is the Odd one?????


class phonebook {
char name[80]; int areacode; int prefix; int num;
public: phonebook() { };
phonebook(char *n, int a, int p, int nm) {
strcpy(name, n); areacode = a; prefix = p; num = nm; }
friend ostream &operator<<(ostream &stream, phonebook o);
friend istream &operator>>(istream &stream, phonebook &o);
};
// Input name and telephone number.
istream &operator>>(istream &stream, phonebook &o) {
cout << "Enter name: "; stream >> o.name;
cout << "Enter area code: "; stream >> o.areacode;
cout << "Enter prefix: "; stream >> o.prefix;
cout << "Enter number: "; stream >> o.num;
return stream; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


353

// Display name and phone number.


ostream &operator<<(ostream &stream, phonebook o) {
stream << o.name << " ";
stream << "(" << o.areacode << ") ";
stream << o.prefix << "-" << o.num << "\n";
return stream; }
void main() { phonebook a; cin >> a; cout << a; }

Enter name: Raja


Enter area code: 111
Enter Prefix: 555
Enter number: 9991
Raja (111) 555-9991

(PN) (MCA)(2010-11/ EVEN) (2010-13)


354

Run Time Type Identification

(PN) (MCA)(2010-11/ EVEN) (2010-13)


355

What’s RTTI?

 RTTI: Runtime Type Identification

The ability to identify the type of a given object at runtime

 What it is for?

Type identification
Inheritance hierarchy
String based method invocation
Exception handling

(PN) (MCA)(2010-11/ EVEN) (2010-13)


356

 C++ implements polymorphism through the use of class


hierarchies, virtual functions, and base-class pointers

 Since base-class pointers may be used to point to objects of the


base class or any object derived from that base, it is
not always possible to know in advance what type of object will
be pointed to by a base pointer at any given moment in time

 This determination must be made at run time, using run-time


type identification

 To obtain an object's type, use typeid

 You must include the header <typeinfo.h> in order to use typeid

(PN) (MCA)(2010-11/ EVEN) (2010-13)


#include <iostream.h>#include <typeinfo> 357
class myclass1 { // ... };
class myclass2 { // ... };
void main() {
int i, j; float f; char *p;
myclass1 ob1; myclass2 ob2;
cout << "The type of i is: " << typeid(i).name();
cout << "The type of f is: " << typeid(f).name();
cout << "The type of p is: " << typeid(p).name();
cout << "The type of ob1 is: " << typeid(ob1).name();
cout << "The type of ob2 is: " << typeid(ob2).name();
if(typeid(i) == typeid(j))
cout << "The types of i and j are the same\n";
if(typeid(i) != typeid(f))
cout << "The types of i and f are not the same\n";
if(typeid(ob1) != typeid(ob2))
cout << "ob1 and ob2 are of differing types\n";
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


358

The type of i is: int


The type of f is: float
The type of p is: char *
The type of ob1 is: class myclass1
The type of ob2 is: class myclass2

The types of i and j are the same


The types of i and f are not the same
ob1 and ob2 are of differing types

(PN) (MCA)(2010-11/ EVEN) (2010-13)


359

 The most important use of typeid occurs when it is applied


through a pointer of a polymorphic base class

 In this case, it will automatically return the type of the


actual object being pointed to, which may be a base-class
object or an object derived from that base

 Remember, a base-class pointer can point to objects of the


base class or of any class derived from that base

 Thus, using typeid, you can determine at run time the


type of the object that is being pointed to by a base-class
pointer

(PN) (MCA)(2010-11/ EVEN) (2010-13)


360
#include <iostream> #include <typeinfo>
void main()
class Mammal {
{
public: Mammal *p, AnyMammal;
virtual bool lays_eggs() Cat cat; Platypus platypus;
{ return false; } p = &AnyMammal;
cout << "p is pointing to an object of
// Mammal is polymorphic type ";
// ... cout << typeid(*p).name();
}; p = &cat;
cout << "p is pointing to an object of
class Cat: public Mammal { type ";
public: cout << typeid(*p).name() ;
// ... p = &platypus;
cout << "p is pointing to an object of
};
type ";
class Platypus: public Mammal { cout << typeid(*p).name() ;
public: }
bool lays_eggs()
{ return true; }
// ...
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


p is pointing to an object of type class Mammal 361

p is pointing to an object of type class Cat


p is pointing to an object of type class Platypus

 when typeid is applied to a base-class pointer of a


polymorphic type, the type of object pointed to will be
determined at run time, as shown by the output produced
by the program
 In all cases, when typeid is applied to a pointer of a
nonpolymorphic class heirarchy, then the base type of the
pointer is obtained
 That is, no determination of what that pointer is actually
pointing to is made
 For example, comment out the virtual keyword before the
function lays_eggs() in Mammal class

p is pointing to an object of type class Mammal


p is pointing to an object of type class Mammal
p is pointing to an object of type class Mammal
(PN) (MCA)(2010-11/ EVEN) (2010-13)
References to an object of a polymorphic class hierarchy 362
work the same as pointers

When typeid is applied to a reference to an object of a


polymorphic class, it will return the type of the object actually
being referred to, which may be of a derived type
#include <iostream> #include <typeinfo>
class Mammal { public:
virtual bool lays_eggs() { return false; }// Mammal is polymorphic
// ... };
class Cat: public Mammal {
public: // ... };
class Platypus: public Mammal {
public: bool lays_eggs() { return true; }
// ... };
void WhatMammal(Mammal &ob) {
cout << "ob is referencing an object of type ";
cout << typeid(ob).name(); }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


363

void main()
Mammal AnyMammal;
Cat cat;
Platypus platypus;
WhatMammal(AnyMammal);
WhatMammal(cat);
WhatMammal(platypus);
}
ob is referencing an object of type class Mammal
ob is referencing an object of type class Cat
ob is referencing an object of type class Platypus

(PN) (MCA)(2010-11/ EVEN) (2010-13)


364
A Simple application of Run- Time Type ID

#include <iostream> #include <typeinfo> #include <cstdlib>


class Mammal {
public:
virtual bool lays_eggs() {return false;}// Mammal is polymorphic
// ... };
class Cat: public Mammal {
public: // ... };
class Platypus: public Mammal {
public: bool lays_eggs() { return true; }
// ... };
class Dog: public Mammal {
public: // ... };
Mammal *factory() {
switch(rand() % 3 ) {
case 0: return new Dog; case 1: return new Cat;
case 2: return new Platypus; } }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


365
void main() {
Mammal *ptr; //pointer to base class Object is Cat
int i; int c=0, d=0, p=0; Object is Cat
Object is Dog
// generate and count objects
Object is Cat
for(i=0; i<10; i++) { Object is Platypus
ptr = factory(); // generate an object Object is Cat
cout<< "Object is"<<typeid(*ptr).name(); Object is Cat
Object is Dog
// count it
Object is Dog
if(typeid(*ptr) == typeid(Dog)) d++; Object is Cat
if(typeid(*ptr) == typeid(Cat)) c++;
if(typeid(*ptr) == typeid(Platypus)) p+ Animals generated:
+; } Dogs: 3
Cats: 6
cout << "Animals generated:\n";
Platypuses: 1
cout << " Dogs: " << d;
cout << " Cats: " << c;
cout << " Platypuses: " << p;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


366
Applying typeid on Template Class
#include <iostream> #include<typeinfo>
template <class T> class myclass { T a;
public:
myclass(T i) { a = i; } // ... };
void main() {
myclass<int> o1(10), o2(9);
myclass<double> o3(7.2);
cout << "Type of o1 is ";<<typeid(o1).name() ;
cout << "Type of o2 is “<<typeid(o2).name();
cout << "Type of o3 is “<<typeid(o3).name();
if(typeid(o1) == typeid(o2))
cout << "o1 and o2 are the same type\n";
if(typeid(o1) == typeid(o3)) cout << "Error\n";
else cout << "o1 and o3 are different types\n";
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


367

Type of o1 is class myclass<int>


Type of o2 is class myclass<int>
Type of o3 is class myclass<double>
o1 and o2 are the same type
o1 and o3 are different types

(PN) (MCA)(2010-11/ EVEN) (2010-13)


368

Exception Handling

What is exception?
C++ can detect run-time errors, but does not have any idea
what to do about them. The user may know how to cope with
such errors but cannot detect them. The notion of an exception
is provided to help deal with such problems.

 An exception is an object that is ‘thrown’ from the site of the


error while program in execution

 Such exception can be ‘caught’ by an appropriate ‘exception


handle’ designed to handle that particular type of error

(PN) (MCA)(2010-11/ EVEN) (2010-13)


369

Exception Types

 Exceptions are of two kinds:

Synchronous Exceptions:
 Errors such as out-of-range index, divide by zero,
and overflow,underflow belong to synchronous
exceptions

Asynchronous Exceptions:
 The errors that are caused by events beyond the
control of the program such as keyboard interrupts,
disk failure,hardware malfunctions and so on on are
called asynchronous exceptions

(PN) (MCA)(2010-11/ EVEN) (2010-13)


370

This section will deal with the concept in handling synchronous


exceptions

The purpose of the exception handling is to provide a mechanism


to detect and report the ‘exceptional circumstances’ in the program
so that appropriate action can be taken.

This process involves separate error handling code that performs


the following tasks
 Identify the problem (Hit the exception)
 Report that an error has occurred (Throw the exception)
 Receive the error information (Catch the exception)
 Take corrective actions (Handles the exception)

(PN) (MCA)(2010-11/ EVEN) (2010-13)


371

 The error handling code basically consists of two segments,


one segment is used to detect error and to throw exceptions

 The second segment is to catch the exceptions and to take


appropriate actions

(PN) (MCA)(2010-11/ EVEN) (2010-13)


372

Exception Handling Model

try block

Detects and throws


an exception

Exception object

catch block

Catches and handles


an exception

(PN) (MCA)(2010-11/ EVEN) (2010-13)


373

 The keyword try is used to preface a block of statements


surrounded by braces which may be generating exceptions;
this block of statements is known as try block

 When an exception is detected, it is thrown using a throw


statement in the try block

 A catch block is defined by the keyword catch catches the


exception thrown by the throw statement in the try block and
handles it appropriately

(PN) (MCA)(2010-11/ EVEN) (2010-13)


374

Exception Handling: Format

try
{
……
throw exception; // block of statements
// which detects and
// throws an exception
}

catch (type arg) // catches exception


{
……….
………. // block of statements that
………. // handles the exception
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


375

Illustratation of try-catch Concept

void main() {
int a,b;
cout<<“Enter values of a and b \n";
cin>>a; cin>>b;
int x= a-b;
try
{
if(x!=0)
{
cout<<"Result (a/x) =" <<a/x<<"\n";
}
else
{ // there is an exception
throw (x); // throws int object
}
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


376

catch (int i) // catches the exception


{
cout<<“Exception caught : x="<<x<<"\m";
}
}

Enter values of a and b 8 2


Result (a/x) = 1.33
Enter values of a and b 8 8
Exception caught : x=0

(PN) (MCA)(2010-11/ EVEN) (2010-13)


377

 Most often, exceptions are thrown by functions that are


invoked from within the try block

 The point at which the throw block is executed is called


the throw point

 Once an exception is thrown to the catch block, control


cannot return to the throw point

(PN) (MCA)(2010-11/ EVEN) (2010-13)


378

Throw point
Throw exception Invoke
function Function that causes
an exception

try block

invokes a function that


contains an exception

catch block

Catches and handles


an exception

(PN) (MCA)(2010-11/ EVEN) (2010-13)


379

Invoking Function that Generates Exception

void divide (int x, int y, intz){


cout << " inside the function \n “;
if (( x-y) !=0)
{
int R = z/(x–y) ;
cout<<  " Result = “ << R << “\n”;
}
else // there is a problem
{
throw (x-y); // throw point
}
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


380

void main() {
try { cout<< ” inside the try block \n”;
divide(20,10,30); // Invoke divide
divide(30,30,60); // Invoke divide
}
catch (int i) {
cout<< “ caught the exception \n “;
}
}
inside the try block
inside the function
Result = -3
Caught the exception

(PN) (MCA)(2010-11/ EVEN) (2010-13)


381

Throwing Mechanism

When an exception that 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.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


382

Catching Mechanism

A catch block looks like a function definition and is of the form:


catch (type arg)
{
// statements for managing exceptions
}
The type indicates the type of exception that catch block handles.
The parameter arg is an optional parameter name; the catch
statement catches an exception whose type matches with the type
of catch argument,when it is caught, the code in the catch block is
executed.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


383

Multiple Catch Statements

 It is possible that a program segment has more than one condition


to throw an exception; such cases, you can associate more than one
catch statements with a try as shown in the following code
try
{ // try block }
catch (type1 arg)
{ // catch block1 }
catch (type2 arg)
{ // catch block2 }
……….
……….
catch (typeN arg)
{ // catch blockN }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


384

void Xhandler(int test) {


try{ void main() {
if(test) throw test; cout << "Start\n";
else throw "Value is zero"; Xhandler(1); Xhandler(2);
} Xhandler(0); Xhandler(3);
catch(int i) { cout << “End"; }
cout << "Caught Exception #: " << i;
}
Start
catch(const char *str) {
Caught Exception #:1
cout << "Caught a string: ";
Caught Exception #:2
cout << str << '\n';
} Caught a string: Value is zero
} Caught Exception #:3
End

(PN) (MCA)(2010-11/ EVEN) (2010-13)


385

Catch All Exceptions

 In some situations, you may not be able to anticipate all


possible type of exceptions and defining unique catch
handlers to catch the appropriate one

 In such situations you can force a catch statement to


catch all exceptions instead of a certain type alone

For example:
catch ( …)
{
// statements for processing all exceptions
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


386

void test ( int x) {


try
{ if(x==0) throw x; //int
if(x==-1) throw ‘x’; //char
if(x==1) throw 1.0; //float
}
catch(….) // catch all
{
cout<<” caught an exception”;
}
}
void main() {
cout << “ Test for common catch “;
test(-1); test(0); test(1);
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


387

Rethrowing an Exception

 A handler may decide to re-throw the exception caught


without processing it

 In such situations, you may simply invoke throw


without any arguments: 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

(PN) (MCA)(2010-11/ EVEN) (2010-13)


void Xhandler() 388
{
try { throw "hello"; // throw a char * }
catch(const char *) { // catch a char *
cout << "Caught char * inside Xhandler\n";
throw ; // rethrow char * out of function
}
}
void main() {
cout << "Start\n";
try{ Xhandler(); }
catch(const char *) { Start
cout << "Caught char * inside main\n"; Caught char * inside Xhandler
} Caught char * inside main
cout << "End"; } End

(PN) (MCA)(2010-11/ EVEN) (2010-13)


389

Restricting Exceptions

 It is possible to restrict a function to throw only certain


specified exceptions, this is achieved by adding a throw
list clause to the function definition
The general form of using an exception specification is:
ret-type function(arg-list) throw (type-list)
{
……… Function body
}
 If you want to prevent a function from throwing any exception,
simply make the type-list empty, that is:
ret-type function(arg-list) throw()
{
……… Function body
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


390
Testing Throw Exception
Caught an Integer
End of try-catch system

void Xhandler(int test) throw(int, char, double) {


if(test==0) throw test; // throw int
if(test==1) throw 'a'; // throw char
if(test==2) throw 123.23; // throw double
}
void main() {
cout << "Testing Throw Exception\n";
try{
Xhandler(0); // also, try passing 1 and 2 to Xhandler()
}
catch(int i) { cout << "Caught an integer\n"; }
catch(char c) { cout << "Caught char\n"; }
catch(double d) { cout << "Caught double\n"; }
cout<<” End of try-catch system \n”;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


391

Handling Derived-Class Exception

 You need to be careful how you order your catch


statements when trying to catch exception types that
involves base and derived classes because a catch clause
for a base class will also match any class derived from
that base

 Thus, if you want to catch exceptions of both a base and


derived class type, put the derived class catch component
first in the catch sequence

 If you don’t do this, the base class catch will also catch
all derived classes

(PN) (MCA)(2010-11/ EVEN) (2010-13)


392
void main() {
class B { D derived;
}; try {
class D: public B { throw derived;
}; }
catch(B b) {
cout << "Caught a base class.\n";
}
catch(D d) {
cout << "This won't execute.\n";
}
}

Here, because derived is an object that has B as a base


class, it will be caught by the first catch clause and second
catch clause will never execute.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


393

Applying Exception

void main() {
void divide(double a, double b) double i, j;
{ do {
try { cout<< "Enter numerator(0 to stop):";
if(!b) throw b; // check for cin >> i;
divide-by-zero
cout << "Enter denominator: ";
cout << "Result: " << a/b;
cin >> j;
}
divide(i, j);
catch (double b) {
} while(i != 0);
cout << "Can't divide by zero;}
}
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


394

Standard Template Library (STL)

 The standard template library consists of three foundational


items: containers, algorithms, and iterators

 These items work in conjunction with one another to provide


off-the-shelf solutions to a variety of programming problems

(PN) (MCA)(2010-11/ EVEN) (2010-13)


395

Containers

 Containers are objects that hold other objects, and there


are several different types

 For example, the vector class defines a dynamic array,


deque creates a double-ended queue, and list provides a
linear list

 These containers are called sequence containers because in


STL terminology, a sequence is a linear list

 In addition to the basic containers, the STL also defines


associative containers, which allow efficient retrieval of
values based on keys
(PN) (MCA)(2010-11/ EVEN) (2010-13)
396

 For example, a map provides access to values with unique


Keys; thus, a map stores a key/value pair and allows a
value to be retrieved given its key

 Each container class defines a set of functions that may


be applied to the container

 For example, a list container includes functions that


insert, delete, and merge elements

 A stack includes functions that push and pop values

(PN) (MCA)(2010-11/ EVEN) (2010-13)


397

Containers defined by STL

(PN) (MCA)(2010-11/ EVEN) (2010-13)


398

Algorithms

 Algorithms act on containers.

 They provide the means by which you will


manipulate the contents of containers.

 Their capabilities include initialization, sorting,


searching, and transforming the contents of
containers

(PN) (MCA)(2010-11/ EVEN) (2010-13)


399
Iterators
 Iterators are objects that are, more or less, pointers
 They give you the ability to cycle through the contents of a
container in much the same way that you would use a
pointer to cycle through an array
Iterator Access Allowed
Random Access Access Store and retrieve values. Elements
may be accessed randomly.
Bidirectional Store and retrieve values. Forward and
backward moving.
Forward Store and retrieve values. Forward moving
only.
Input Retrieve, but not store values. Forward
moving only
Output Store, but not retrieve values. Forward
moving only.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


400

General Idea of STL Containers

 Each container component offers certain benefits and trade-offs


For example, a vector is very good when a random-access,
array-like object is required and not too many insertions or
deletions are needed.
 A list offers low-cost insertion and deletion but trades away
speed
 A map provides an associative container, but of course incurs
additional overhead
 Once you have chosen a container, you will use its member
functions to add elements to the container, access or modify
those elements, and delete elements
 Except for bitset, a container will automatically grow as needed
when elements are added to it and shrink when elements are
removed

(PN) (MCA)(2010-11/ EVEN) (2010-13)


401

 Elements can be added to and removed from a container a


number of different ways

 For example, both the sequence containers (vector, list, and


deque) and the associative containers (map, multimap, set,
and multiset) provide a member function called insert() ,
which inserts elements into a container, and erase() , which
removes elements from a container

 The sequence containers also provide push_back() and


push_front() , which add an element to the end or the
beginning of a container, respectively

(PN) (MCA)(2010-11/ EVEN) (2010-13)


402

 These functions are probably the most common way that individual
elements are added to a sequence container

 You can remove individual elements from a sequence container by using


pop_back() and pop_front() , which remove elements from the end and
start of the container

 One of the most common ways to access the elements within a container
is through an iterator

 The sequence and the associative containers provide the member


functions begin() and end() , which return iterators to the start and end of
the container, respectively

 These iterators are very useful when accessing the contents of a container

(PN) (MCA)(2010-11/ EVEN) (2010-13)


403
 For example, to cycle through a container, you can obtain an iterator to
its beginning using begin() and then increment that iterator until its
value is equal to end()

 The associative containers provide the function find() , which is used to


locate an element in an associative container given its key

 Since associative containers link a key with its value, find() is how most
elements in such a container are located

 Since a vector is a dynamic array, it also supports the standard array-


indexing syntax for accessing its elements

 Once you have a container that holds information, it can be manipulated


using one or more algorithms

(PN) (MCA)(2010-11/ EVEN) (2010-13)


404

Vector – Sequential Container

 The most general-purpose of the containers is vector

 The vector class supports a dynamic array; this is an array that


can grow and shrink as needed

 As you know, in C++ the size of an array is fixed at compile


time, the size of the array cannot be adjusted at run time to
accommodate changing program conditions

 A vector solves this problem by allocating memory as needed


Since the vector is dynamic, you can still use the standard
array subscript notation to access its elements

(PN) (MCA)(2010-11/ EVEN) (2010-13)


405

Syntax of Vector STL

template <class T, class Allocator = allocator<T>> class vector


Here, T is the type of data being stored and Allocator specifies the
allocator, which defaults to the standard allocator

vector<int> iv; // create zero-length int vector


vector<char> cv(5); // create 5-element char vector
vector<char> cv(5, 'x'); // initialize a 5-element char vector
vector<int> iv2(iv); // create int vector from an int vector

The following comparison operators are defined for vector:


==, <, <=, !=, >, >=

(PN) (MCA)(2010-11/ EVEN) (2010-13)


406
Member Functions defined by vector

(PN) (MCA)(2010-11/ EVEN) (2010-13)


407

(PN) (MCA)(2010-11/ EVEN) (2010-13)


408

#include <iostream.h>
#include <vector.h>
#include <ctype.h>
void main() {
vector<char> v(10); // create a vector of length 10
int i;
// display original size of v
cout << "Size = " << v.size() << endl;
// assign the elements of the vector some values
for(i=0; i<10; i++) v[i] = i + 'a';
// display contents of vector
cout << "Current Contents:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";

(PN) (MCA)(2010-11/ EVEN) (2010-13)


409

cout << "Expanding vector\n";


/* put more values onto the end of the vector,
it will grow as needed */
for(i=0; i<10; i++) v.push_back(i + 10 + 'a');
// display current size of v
cout << "Size now = " << v.size() << endl;
// display contents of vector
cout << "Current contents:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
// change contents of vector
for(i=0; i<v.size(); i++) v[i] = toupper(v[i]);
cout << "Modified Contents:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


410

Size = 10
Current Contents:
abcdefghij

Expanding vector
Size now = 20
Current contents:
abcdefghijklmnopqrst

Modified Contents:
ABCDEFGHIJKLMNOPQRST

(PN) (MCA)(2010-11/ EVEN) (2010-13)


411

Accessing a Vector through an Iterator

#include <vector.h>
#include <ctype.h>
void main() {
vector<char> v(10); // create a vector of length 10
int i; vector<char>::iterator p; // create an iterator
// assign elements in vector a value
p = v.begin();
i = 0;
while(p != v.end())
*p++ = i++ + 'a';

(PN) (MCA)(2010-11/ EVEN) (2010-13)


412

// display contents of vector Original contents:


cout << "Original contents:\n";
p = v.begin(); abcdefghij
while(p != v.end())
cout << *p++ << " "; Modified Contents:
// change contents of vector
p = v.begin();
ABCDEFGHIJ
while(p != v.end())
*p++ = toupper(*p);
// display contents of vector
cout << "Modified Contents:\n";
p = v.begin();
while(p != v.end())
cout << *p++ << " ";
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


413
Inserting and Deleting Elements in a Vector

#include <iostream.h>
#include <vector.h>
void main() {
vector<char> v(10); vector<char> v2;
char str[] = "<Vector>"; int i;
// initialize v
for(i=0; i<10; i++) v[i] = i + 'a';
// copy characters in str into v2
for(i=0; str[i]; i++) v2.push_back(str[i]);
// display original contents of vector
cout << "Original contents of v:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";

(PN) (MCA)(2010-11/ EVEN) (2010-13)


414

vector<char>::iterator p = v.begin();
p += 2; // point to 3rd element
// insert 10 X's into v
v.insert(p, 10, 'X');
// display contents after insertion
cout << "Size after inserting X's = " << v.size() << endl;
cout << "Contents after insert:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
// remove those elements
p = v.begin();
p += 2; // point to 3rd element
v.erase(p, p+10); // remove next 10 elements

(PN) (MCA)(2010-11/ EVEN) (2010-13)


415

// display contents after deletion


cout << "Size after erase = " << v.size() << endl;
cout << "Contents after erase:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";

// Insert v2 into v
v.insert(p, v2.begin(), v2.end());
cout << "Size after v2's insertion = ";
cout << v.size() << endl;
cout << "Contents after insert:\n";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


416

Original contents of v:
abcdefghij
Size after inserting X's = 20
Contents after insert:
abXXXXXXXXXXcdefghij
Size after erase = 10
Contents after erase:
abcdefghij
Size after v2's insertion = 18
Contents after insert:
ab<Vector>cdefghij

(PN) (MCA)(2010-11/ EVEN) (2010-13)


417

Storing Class Objects in a Vector

#include <vector.h>
#include <stdlib.h>
class DailyTemp { int temp;
public:
DailyTemp() { temp = 0; }
DailyTemp(int x) { temp = x; }
double get_temp() { return temp; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


418
void main() {
vector<DailyTemp> v; int i;
for(i=0; i<7; i++)
v.push_back(DailyTemp(60 + rand()%30));
cout << "Farenheit temperatures:\n";
for(i=0; i<v.size(); i++)
cout << v[i].get_temp() << " ";
// convert from Farenheit to Centigrade
for(i=0; i<v.size(); i++)
v[i] = (int)(v[i].get_temp()-32) * 5/9 ;
cout << "Centigrade temperatures:";
for(i=0; i<v.size(); i++)
cout << v[i].get_temp();
}
Farenheit temperatures:
70 62 70 76 67 75 85
Centigrade temperatures:
21 16 21 24 19 23 29

(PN) (MCA)(2010-11/ EVEN) (2010-13)


419

Lists – Sequential Container

 The list class supports a bidirectional, linear list

 Unlike a vector, which supports random access, a list


can be accessed sequentially only

 Since lists are bidirectional, they may be accessed front to


back or back to front

A list has this template specification:


template <class T, class Allocator = allocator<T>> class list

Here, T is the type of data stored in the list. The allocator is


specified by Allocator, which defaults to the standard allocator.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


420

The following comparison operators are defined for list:


==, <, <=, !=, >, >=

 Like vectors, elements may be put into a list by using the


push_back() function You can put elements on the front of the
list by using push_front()

 An element can also be inserted into the middle of a list by using


insert()

 Two lists may be joined using splice()

 One list may be merged into another using merge()

(PN) (MCA)(2010-11/ EVEN) (2010-13)


421
Member Functions defined by List

(PN) (MCA)(2010-11/ EVEN) (2010-13)


422

(PN) (MCA)(2010-11/ EVEN) (2010-13)


423

(PN) (MCA)(2010-11/ EVEN) (2010-13)


424
Size = 10
Contents: 0 1 2 3 4 5 6 7 8 9

Contents modified: 100 101 102 103 104 105 106 107 108 109

#include <list.h>
void main() {
list<int> lst; // create an empty list int i;
for(i=0; i<10; i++) lst.push_back(i);
cout << "Size = " << lst.size() << endl;
cout << "Contents: ";
list<int>::iterator p = lst.begin();
while(p != lst.end()) { cout << *p << " "; p++; }
// change contents of list
p = lst.begin();
while(p != lst.end()) { *p = *p + 100; p++; }
cout << "Contents modified: ";
p = lst.begin();
while(p != lst.end()) { cout << *p << " "; p++; }
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


425
#include <list.h>
void main() {
list<int> lst; // create an empty list int i;
for(i=0; i<10; i++) lst.push_back(i);
cout << "List printed forwards:\n";
list<int>::iterator p = lst.begin();
while(p != lst.end()) { cout << *p << " "; p++; }
cout << "List printed backwards:\n";
p = lst.end();
while(p != lst.begin()) {
p--; // decrement pointer before using cout << *p << " ";
}
}

List printed forwards:


0123456789
List printed backwards:
9876543210

(PN) (MCA)(2010-11/ EVEN) (2010-13)


426

push_front() vs Push_back()

#include <list.h> Contents of lst1:


0123456789
void main() { Contents of lst2:
list<int> lst1, lst2; int i; 9876543210
for(i=0; i<10; i++) lst1.push_back(i);
for(i=0; i<10; i++) lst2.push_front(i);
list<int>::iterator p;
cout << "Contents of lst1:\n";
p = lst1.begin();
while(p != lst1.end()) { cout << *p << " "; p++; }
cout << "Contents of lst2:\n";
p = lst2.begin();
while(p != lst2.end()) { cout << *p << " "; p++; }
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


427
Sort a List

Original contents:
130 10982 1090 11656 7117 17595 6415
#include <list.h> 22948 31126 9004
#include <stdlib.h> Sorted contents:
void main() { 130 1090 6415 7117 9004 10982 11656
list<int> lst; int i; 17595 22948 31126
// create a list of random integers
for(i=0; i<10; i++)
lst.push_back(rand());
cout << "Original contents:\n";
list<int>::iterator p = lst.begin();
while(p != lst.end()) { cout << *p << " "; p++; }
// sort the list
lst.sort();
cout << "Sorted contents:\n";
p = lst.begin();
while(p != lst.end()) { cout << *p << " "; p++; }
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


428

Merging one list with another

 One ordered list may be merged with another; the


result is an ordered list that contains the contents of
the two original lists

 The new list is left in the invoking list, and the second
list is left empty

(PN) (MCA)(2010-11/ EVEN) (2010-13)


429

#include <list.h>
void main() {
list<int> lst1, lst2; int i;
for(i=0; i<10; i+=2) lst1.push_back(i);
for(i=1; i<11; i+=2) lst2.push_back(i);
cout << "Contents of lst1:\n";
list<int>::iterator p = lst1.begin();
while(p != lst1.end()) { cout << *p << " "; p++; }
cout << "Contents of lst2:\n";
p = lst2.begin();
while(p != lst2.end()) { cout << *p << " "; p++; }
// now, merge the two lists
lst1.merge(lst2); if(lst2.empty()) cout<<"lst2 is now empty";

(PN) (MCA)(2010-11/ EVEN) (2010-13)


430

cout << "\n Contents of lst1 after merge:\n";


p = lst1.begin();
while(p != lst1.end()) { cout << *p << " "; p++; }
}
Contents of lst1:
02468
Contents of lst2:
13579
lst2 is now empty
Contents of lst1 after merge:
0123456789
(PN) (MCA)(2010-11/ EVEN) (2010-13)
431

Storing a Class Object in a List

#include <list.h>
#include <string.h>
class myclass {
int a, b,sum;
public:
myclass() { a = b = 0; }
myclass(int i, int j) {
a = i; b = j; sum = a + b; }
int getsum() { return sum; }
friend bool operator<(const myclass &o1,const myclass &o2);
};
bool operator<(const myclass &o1, const myclass &o2)
{ return o1.sum < o2.sum; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


void main() { 432
int i;
// create first list
list<myclass> lst1;
for(i=0; i<10; i++) lst1.push_back(myclass(i, i));
cout << "First list: ";
list<myclass>::iterator p = lst1.begin();
while(p != lst1.end()) {cout << p->getsum() << " "; p++; }
// create a second list
list<myclass> lst2;
for(i=0; i<10; i++) lst2.push_back(myclass(i*2, i*3));
cout << "Second list: ";
p = lst2.begin();
while(p != lst2.end()) {cout << p->getsum() << " "; p++; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


433
// now, merget lst1 and lst2
lst1.merge(lst2);

// display merged list


cout << "Merged list: ";
p = lst1.begin();
while(p != lst1.end()) {cout<< p->getsum()<< " "; p++; }
}

First list: 0 2 4 6 8 10 12 14 16 18
Second list: 0 5 10 15 20 25 30 35 40 45
Merged list: 0 0 2 4 5 6 8 10 10 12 14 15 16 18 20 25 30 35 40 45

(PN) (MCA)(2010-11/ EVEN) (2010-13)


434

Maps – Associative Container

 The map class supports an associative container in which unique


keys are mapped with values

 In essence, a key is simply a name that you give to a value, once


a value has been stored, you can retrieve it by using its key

 Thus, in its most general sense, a map is a list of key/value pairs

 The power of a map is that you can look up a value given its key

For example, you could define a map that uses a person's name
as its key and stores that person's phone number as its value

(PN) (MCA)(2010-11/ EVEN) (2010-13)


435

 A map can hold only unique keys; duplicate keys are not allowed

 To create a map that allows nonunique keys, use multimap

 The map container has the following template specification:

template <class Key, class T, class Comp = less<Key>,


class Allocator = allocator<T>> class map

Here, Key is the data type of the keys, T is the data type of the
values being stored (mapped), and Comp is a function that
compares two keys which defaults to the standard less() utility
function object
 The following comparison operators are defined for map
==, <, <=, !=, >, >=

(PN) (MCA)(2010-11/ EVEN) (2010-13)


436

Member Functions defined by Map

(PN) (MCA)(2010-11/ EVEN) (2010-13)


437

(PN) (MCA)(2010-11/ EVEN) (2010-13)


438
A 65
Enter key: c
Key not in map. B 66
Enter key: C
Its ASCII value is 67 C 67
#include <map.h>
void main() { D 68
map<char, int> m; int i;
// put pairs into map E 69
for(i=0; i<26; i++) {
m.insert(pair<char, int>('A'+i, 65+i)); F 70
}
char ch; cout << "Enter key: "; cin >> ch;
… …
map<char, int>::iterator p;
// find value given key
… …
p = m.find(ch); if(p != m.end())
cout << "Its ASCII value is " << p->second;
else cout << "Key not in map.\n";
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


439

Storing Class Objects in a Map

#include <map.h>
#include <string.h>
class name { Tom 555-4533
char str[40]; Chris 555-9678
public:
John 555-8195
name() { strcpy(str, ""); }
name(char *s) { strcpy(str, s); } Rachel 555-0809
char *get() { return str; }
};
// Must define less than relative to name objects.
bool operator<(name a, name b)
{ return strcmp(a.get(), b.get()) < 0; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


440
class phoneNum {
char str[80];
public:
phoneNum() { strcmp(str, ""); }
phoneNum(char *s) { strcpy(str, s); }
char *get() { return str; }
};

(PN) (MCA)(2010-11/ EVEN) (2010-13)


441

void main() {
map<name, phoneNum> directory;
// put names and numbers into map
directory.insert(pair<name,phoneNum>(name("Tom"),
phoneNum("555-4533")));
directory.insert(pair<name,phoneNum>(name("Chris"),
phoneNum("555-9678")));
directory.insert(pair<name,phoneNum>(name("John"),
phoneNum("555-8195")));
directory.insert(pair<name,phoneNum>(name("Rachel"),
phoneNum("555-0809")));

(PN) (MCA)(2010-11/ EVEN) (2010-13)


442
// given a name, find number
char str[80]; cout << "Enter name: "; cin >> str;
map<name, phoneNum>::iterator p;
p = directory.find(name(str));
if(p != directory.end())
cout << "Phone number: " <<p->second.get();
else cout << "Name not in directory.\n";
}
Enter name: john
Name not in directory.

Enter name: John


Phone number: 555-8195

(PN) (MCA)(2010-11/ EVEN) (2010-13)


443

Exploring Algorithm

 Algorithms act on containers; although each container provides


support for its own basic operation, the standard algorithms
support more complex actions

 Standard algorithm support to work with two different types of


containers at the same time

 To use STL algorithms, include <algorithm> in source code

 The STL defines a large number of algorithms, refer text book

(PN) (MCA)(2010-11/ EVEN) (2010-13)


444

Algorithm - Counting

 One of the most basic operations that you can perform


on a sequence is to count its contents

 To do this, you can use either count() or count_if()


Their general forms are shown here:

template <class InIter, class T>


size_t count(InIter start, InIter end, const T &val);

template <class InIter, class UnPred>


size_t count_if(InIter start, InIter end, UnPred pfn);

(PN) (MCA)(2010-11/ EVEN) (2010-13)


445

#include <vector.h> #include <cstdlib.h> #include<algorithm.h>


void main() {
vector<bool> v; int i;
for(i=0; i < 10; i++) {
if(rand() % 2) v.push_back(true);
else v.push_back(false); }
cout << "Sequence:\n";
for(i=0; i<v.size(); i++)
cout << boolalpha << v[i] << " "; cout << endl;
i=count(v.begin(), v.end(), true);cout <<i<<"elements are true.";
}
Sequence:
false false false false true true true false false false
3 elements are true.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


446
Sequence:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
6 numbers are divisible by 3.

#include <vector.h>
#include <algorithm.h>
This is a unary predicate that determines if number is divisible by 3
bool dividesBy3(int i) {
return i%3== 0? true: false; }
void main() {
vector<int> v; int i;
for(i=1; i < 20; i++) v.push_back(i);
cout << "Sequence:\n";
for(i=0; i<v.size(); i++)
cout << v[i] << " ";
i = count_if(v.begin(), v.end(), dividesBy3);
cout << i << " numbers are divisible by 3.\n";
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


447

Algorithm for Removing and Replacing Elements

 Sometimes it is useful to generate a new sequence that consists of


only certain items from an original sequence; One algorithm that
does this is remove_copy()

Its general form is shown here:


template <class InIter, class OutIter, class T>
OutIter remove_copy(InIter start, InIter end,
OutIter result, const T &val);

The remove_copy() algorithm copies elements from the


specified range, removing those that are equal to val. It puts the
result into the sequence pointed to by result and returns an
iterator to the end of the result. The output container must be
large enough to hold the result.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


448

 To replace one element in a sequence with another when a


copy is made, use replace_copy()
Its general form is shown here:

template <class InIter, class OutIter, class T>


OutIter replace_copy(InIter start, InIter end,
OutIter result, const T &old, const T &new);

The replace_copy() algorithm copies elements from the


specified range, replacing elements equal to old with new. It puts
the result into the sequence pointed to by result and returns an
iterator to the end of the result. The output container must be
large enough to hold the result.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


449

#include <vector.h> #include <algorithm.h>


void main() {
char str[] = "The STL is power programming.";
vector<char> v, v2(30); int i;
for(i=0; str[i]; i++) v.push_back(str[i]);
// **** demonstrate remove_copy ****
cout<<"Input sequence:"; for(i=0; i<v.size(); i++) cout << v[i];
// remove all spaces
remove_copy(v.begin(), v.end(), v2.begin(), ' ');
cout << "Result after removing spaces:\n";
for(i=0; i<v2.size(); i++) cout << v2[i];
// **** now, demonstrate replace_copy ****
cout<<"Input sequence:";for(i=0; i<v.size(); i++) cout << v[i];

(PN) (MCA)(2010-11/ EVEN) (2010-13)


450
// replace spaces with colons
replace_copy(v.begin(), v.end(), v2.begin(), ' ', ':');
cout << "Result after repacing spaces with colons:\n";
for(i=0; i<v2.size(); i++) cout << v2[i];
}
Input sequence:
The STL is power programming.
Result after removing spaces:
TheSTLispowerprogramming.

Input sequence:
The STL is power programming.
Result after repacing spaces with colons:
The:STL:is:power:programming.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


451

Reversing a Sequence

#include <vector.h> #include <algorithm.h>// gcc <algo.h>


void main() {
vector<int> v; int i;
for(i=0; i<10; i++) v.push_back(i);
cout << "Initial: ";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
reverse(v.begin(), v.end());
cout << "Reversed: ";
for(i=0; i<v.size(); i++) cout << v[i] << " ";
}

Initial: 0 1 2 3 4 5 6 7 8 9
Reversed: 9 8 7 6 5 4 3 2 1 0

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Original contents of vals:
123456789
Transforming a sequence
452

Transformed contents of vals:


1 0.5 0.333333 0.25 0.2 0.166667 0.142857 0.125 0.111111
#include <list.h> #include <algorithm.h>
// A simple transformation function.
double reciprocal(double i) {
return 1.0/i; // return reciprocal }
void main() { list<double> vals; int i;
// put values into list
for(i=1; i<10; i++) vals.push_back((double)i);
cout << "Original contents of vals:\n";
list<double>::iterator p = vals.begin();
while(p != vals.end()) cout << *p++ << " ";
// transform vals
transform(vals.begin(), vals.end(),vals.begin(), reciprocal);
cout << "Transformed contents of vals:\n";
p = vals.begin();
while(p != vals.end()) cout << *p++ << " "; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


453
Function Object

Binary Function Object Unary Function Object


plus logical_not
minus
multiplies negate
divides
modulus
equal_to
not_equal_to
greater
greater_equal
less
less_equal
logical_and
logical_or
(PN) (MCA)(2010-11/ EVEN) (2010-13)
454

 The function objects perform the operations specified by


their names

 The built-in function objects are template classes that


overload operator() , which returns the result of the
specified operation on whatever type of data you select

 For example, to invoke the binary function object plus() ,


use this syntax:
plus<float>()

 The built-in function objects use the header <functional>

(PN) (MCA)(2010-11/ EVEN) (2010-13)


455
Unary Function Object

#include <list.h> #include <functional.h> #include <algorithm.h>


void main() {
list<double> vals; int i;
// put values into list
for(i=1; i<10; i++) vals.push_back((double)i);
cout << "Original contents of vals:\n";
list<double>::iterator p = vals.begin();
while(p++ != vals.end()) cout << *p << " ";
// use the negate function object
transform(vals.begin(),vals.end(),vals.begin(),negate<double>()); // call
function object
cout << "Negated contents of vals:\n";
p = vals.begin();
while(p++ != vals.end()) cout << *p << " ";
}
Original contents of vals: 1 2 3 4 5 6 7 8 9
Negated contents of vals: -1 -2 -3 -4 -5 -6 -7 -8 -9

(PN) (MCA)(2010-11/ EVEN) (2010-13)


456
Binary Function Object

#include <list.h> #include <functional.h> #include <algorithm.h>


void main() {
list<double> vals; list<double> divisors; int i;
// put values into list
for(i=10; i<100; i+=10) vals.push_back((double)i);
for(i=1; i<10; i++) divisors.push_back(3.0);
cout << "Original contents of vals:\n";
list<double>::iterator p = vals.begin();
while(p++ != vals.end()) cout << *p << " ";
// transform vals
transform(vals.begin(), vals.end(),divisors.begin(),vals.begin(),
divides<double>()); // call function object
cout << "Divided contents of vals:\n"; p = vals.begin();
while(p++ != vals.end()) cout << *p << " "; }
Original contents of vals: 10 20 30 40 50 60 70 80 90
Divided contents of vals:
3.33333 6.66667 10 13.3333 16.6667 20 23.3333 26.6667 30

(PN) (MCA)(2010-11/ EVEN) (2010-13)


457

Creating Function Object

#include <list.h> #include <functional.h> #include <algorithm.h>


// A simple function object.
class reciprocal: unary_function<double, double> {
public:
result_type operator()(argument_type i)
{
return (result_type) 1.0/i; // return reciprocal
} };
void main() {
list<double> vals; int i;
// put values into list
for(i=1; i<10; i++) vals.push_back((double)i);
cout << "Original contents of vals:\n";
list<double>::iterator p = vals.begin();
while(p++ != vals.end()) cout << *p << " ";

(PN) (MCA)(2010-11/ EVEN) (2010-13)


458

// use reciprocal function object


transform(vals.begin(), vals.end(),vals.begin(),
reciprocal()); // call function object
cout << "Transformed contents of vals:\n"; p = vals.begin();
while(p++ != vals.end()) cout << *p << " "; }

Original contents of vals:


123456789
Transformed contents of vals:
1 0.5 0.333333 0.25 0.2 0.166667 0.142857 0.125 0.111111

(PN) (MCA)(2010-11/ EVEN) (2010-13)


459

 Notice two important aspects of reciprocal()

 First, it inherits the base class unary_function; this gives it


access to the argument_type and result_type types
 Second, it defines operator() such that it returns the
reciprocal of its argument
 In general, to create a function object, simply inherit the
proper base class and overload operator() as required

(PN) (MCA)(2010-11/ EVEN) (2010-13)


460
Using Binders

 When using a binary function object, it is possible to bind a


value to one of the arguments; this can be useful in many
situations
 For example, you may wish to remove all elements from a
sequence that are greater than some value, such as 8.
 To do this, you need some way to bind 8 to the right-hand
operand of the function object greater()
 That is, you want greater() to perform the comparison
val > 8 for each element of the sequence
 The STL provides a mechanism, called binders, that
accomplishes this There are two binders: bind2nd() and
bind1st() . They take these general forms:
bind1st(binfunc_obj, value)
bind2nd(binfunc_obj, value)

(PN) (MCA)(2010-11/ EVEN) (2010-13)


461

#include <list.h> #include <functional.h>#include <algorithm.h>


void main() {
list<int> lst; list<int>::iterator p, endp; int i;
for(i=1; i < 20; i++) lst.push_back(i);
cout << "Original sequence:\n"; p = lst.begin();
while(p++ != lst.end()) cout << *p << " ";
endp=remove_if(lst.begin(),lst.end(),bind2nd(greater<int>(),8));
cout << "Resulting sequence:\n";
p = lst.begin();
while(p++ != endp) cout << *p << " ";
}
Original sequence:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Resulting sequence: 1 2 3 4 5 6 7 8

(PN) (MCA)(2010-11/ EVEN) (2010-13)


462

The String Class

 C++ already contains some support for strings as null-


terminated character arrays, it may at first seem that
the inclusion of the string class is an exception to this
rule
 Null-terminated strings cannot be manipulated by any
of the standard C++ operators and they cannot take
part in normal C++ expressions

For example, consider this fragment:


char s1[80], s2[80], s3[80];
s1 = "Alpha"; // can't do
s2 = "Beta"; // can't do
s3 = s1 + s2; // error, not allowed

(PN) (MCA)(2010-11/ EVEN) (2010-13)


463

 These operations must be written using library functions, as shown


here:
strcpy(s1, "Alpha");
strcpy(s2, "Beta");
strcpy(s3, s1);
strcat(s3, s2);
 Since null-terminated character arrays are not technically data types
in their own right, the C++ operators cannot be applied to them
 It is the inability to operate on null-terminated strings using the
standard C++ operators that has driven the development of a
standard string class
 By adding a standard string class, it becomes possible to
manage strings in the same way as any other type of data: through
the use of operators

(PN) (MCA)(2010-11/ EVEN) (2010-13)


464

 The other reason for the using standard string class is safety
 There are three reasons for the inclusion of the standard string
class
consistency (a string now defines a data type),
convenience ( standard C++ operators can be applied)
safety (array boundaries will not be overrun)
 To access to the string class, you must include <string> header
 The string class is very large, with many constructors and
member functions

(PN) (MCA)(2010-11/ EVEN) (2010-13)


465

The string class supports several constructors, the prototypes


for three of its most commonly used ones are shown here:
string( );
string(const char *str);
string(const string &str);
The first form creates an empty string object.
The second creates a string object from the null-terminated
string pointed to by str. This form provides a conversion from
null-terminated strings to string objects.
The third form creates a string from another string.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


466
Operators that apply to strings Objects

Operator Meaning
= Assignment
+ Concatenation
+= Concatenation
assignment
== Equality
!= Inequality
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
[] Subscripting
<< ,>> Output , Input

(PN) (MCA)(2010-11/ EVEN) (2010-13)


467
Simple String Example

#include <string.h> // gcc <string>


void main() {
string str1("Alpha"); string str2("Beta");
string str3("Omega"); string str4;
// assign a string
str4 = str1;
cout << str1 << "\n" << str3 << "\n";
// concatenate two strings
str4 = str1 + str2;
cout << str4 << "\n";
// concatenate a string with a C-string
str4 = str1 + " to " + str3;
cout << str4 << "\n";

(PN) (MCA)(2010-11/ EVEN) (2010-13)


468
Alpha
Omega
AlphaBeta
Alpha to Omega
str3 > str1
This is a null-terminated string.
This is a null-terminated string.
Enter a string:stl
// compare strings Stl
if(str3 > str1) cout << "str3 > str1\n";
if(str3 == str1+str2) cout << "str3 == str1+str2\n";
/* A string object can also be assigned a normal string. */
str1 = "This is a null-terminated string.\n"; cout << str1;
// create a string object using another string object
string str5(str1); cout << str5;
// input a string
cout << "Enter a string: "; cin >> str5; cout << str5;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


469

Basic String Manipulations: Insert, Erase, Replace

#include <string.h>
void main(){
string str1("String handling C++ style.");
string str2("STL Power"); cout << "Initial strings:\n";
cout << "str1: " << str1 << "str2: " << str2 << "\n\n";
// demonstrate insert()
cout <<"Insert str2 into str1:\n"; str1.insert(6, str2);cout << str1;
// demonstrate erase()
cout << "Remove 9 characters from str1:\n";
str1.erase(6, 9); cout << str1 <<"\n\n";
// demonstrate replace
cout << "Replace 8 characters in str1 with str2:\n";
str1.replace(7, 8, str2); cout << str1 << endl;
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


470

Initial strings:
str1: String handling C++ style.
str2: STL Power

Insert str2 into str1:


StringSTL Power handling C++ style.

Remove 9 characters from str1:


String handling C++ style.

Replace 8 characters in str1 with str2:


String STL Power C++ style.

(PN) (MCA)(2010-11/ EVEN) (2010-13)


Searching a String 471

The string class defines the constant npos, which is −1;


this constant represents the length of the longest possible
string
#include <string.h> // gcc <string>
void main() {
int i; string s1 = "Quick of Mind, Strong of Body, Pure of Heart";
string s2; i = s1.find("Quick");
if(i!=string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
s2.assign(s1, i, s1.size()); cout << s2;
}
i = s1.find("Strong"); if(i!=string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
s2.assign(s1, i, s1.size()); cout << s2; }

(PN) (MCA)(2010-11/ EVEN) (2010-13)


472

i = s1.find("Pure");
if(i!=string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
s2.assign(s1, i, s1.size()); cout << s2;
}
// find list "of"
i = s1.rfind("of");
if(i!=string::npos) {
cout << "Match found at " << i << endl;
cout << "Remaining string is:\n";
s2.assign(s1, i, s1.size()); cout << s2;
}
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


473
Match found at 0
Remaining string is:
Quick of Mind, Strong of Body, Pure of Heart

Match found at 15
Remaining string is:
Strong of Body, Pure of Heart

Match found at 31
Remaining string is:
Pure of Heart

Match found at 36
Remaining string is:
of Heart

(PN) (MCA)(2010-11/ EVEN) (2010-13)


474

Strings are Containers

 The string class meets all of the basic requirements


necessary to be a container

 Thus, it supports the common container functions, such


as begin() , end() , and size()

 It also supports iterators; therefore, a string object can


also be manipulated by the STL

(PN) (MCA)(2010-11/ EVEN) (2010-13)


475
Strings handling is easy in C++
Strings handling is easy in C++
There are 4 i's in str1
#include <string.h> #include <algorithm.h>
void main() {
string str1("Strings handling is easy in C++");
string::iterator p; int i;
// use size()
for(i=0; i<str1.size(); i++) cout << str1[i];
// use iterator
p = str1.begin();
while(p != str1.end()) cout << *p++;
// use the count() algorithm
i = count(str1.begin(), str1.end(), 'i');
cout << "There are " << i << " i's in str1\n";
}

(PN) (MCA)(2010-11/ EVEN) (2010-13)


476
Putting Strings in other Containers

#include <map.h> #include <string.h> // gcc <string>


void main() {
map<string, string> directory;
directory.insert(pair<string,string>("Tom", "555-4533"));
directory.insert(pair<string, string>("Chris", "555-9678"));
directory.insert(pair<string, string>("John", "555-8195"));
directory.insert(pair<string, string>("Rachel", "555-0809"));
string s; cout << "Enter name: "; cin >> s;
map<string, string>::iterator p; p = directory.find(s);
if(p != directory.end()) cout << "Phone number: "<< p->second;
else cout << "Name not in directory.\n";
}
Enter name: raja Enter name: Tom
Name not in directory. Phone number: 555-4533

(PN) (MCA)(2010-11/ EVEN) (2010-13)

Você também pode gostar