0% found this document useful (0 votes)
41 views312 pages

Bca3rd Sem Unit 1 TO 4 C++

The document discusses object oriented programming concepts including objects, classes, encapsulation, inheritance, polymorphism, and dynamic binding. It compares procedural programming with object oriented programming and C with C++ highlighting differences like classes, structures, functions, memory management and more.

Uploaded by

Shambhavi Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views312 pages

Bca3rd Sem Unit 1 TO 4 C++

The document discusses object oriented programming concepts including objects, classes, encapsulation, inheritance, polymorphism, and dynamic binding. It compares procedural programming with object oriented programming and C with C++ highlighting differences like classes, structures, functions, memory management and more.

Uploaded by

Shambhavi Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 312

Object oriented

programming using c++


UNIT 1 TO UNIT 4

BY ZIA AKBAR 1
Principals of OOPs
Unit 1

BY ZIA AKBAR 2
Procedure oriented programming
• POP Definition
• Procedural Oriented
Programming is one of the
Main program programming methods
where the main focus is on
functions or procedures
required for computation,
Function function instead of data.
Function
1 2 3 • The program is divided into
functions, and the task is
Function Function done sequentially. These
4 5 functions share the global
data or variables, and there is
an exchange of data among
Function
those functions.
6
• Languages: C, Pascal,
FORTRAN

BY ZIA AKBAR 3
characteristics

• Problems are divided into small parts (functions).

• Sharing of global data between functions.

• Problems are solved systematically (algorithm).

• Sharing of data between functions.

• Top down design approach.

BY ZIA AKBAR 4
Object oriented programming
• Object-Oriented Programming
Object
1 • is one of the high-level programming
languages in which a program is
divided into objects.

• Using objects, the programmer can


Object Object
model real-world scenarios. An object
2 communication 3
is an instance of a class and has state
and behavior. The state is the
attributes, or data, whereas Behavior
is called a method.
• Languages: C++, Java, Python
Object
4

BY ZIA AKBAR 5
characteristics
• Emphasis on data rather than functions.

• Data are designed such way it can characterize the


objects.

• Functions and its data tied together in the data


structure.

• Data are hidden and cannot accessed by external


functions.
» Contd…

BY ZIA AKBAR 6
Contd…

• Objects may communicate with each other via


functions.

• New data and functions can be easily added


whenever necessary.

• Bottom up approach in program design.

BY ZIA AKBAR 7
Procedural vs. Object-Oriented
Programming
• The unit in procedural programming is function, and unit in
object-oriented programming is class

• Procedural programming concentrates on creating functions,


while object-oriented programming starts from isolating the
classes, and then look for the methods inside them.

• Procedural programming separates the data of the program


from the operations that manipulate the data, while object-
oriented programming focus on both of them

BY ZIA AKBAR 8
C vs C++

• Similarities
1. Same built-in data types

2. Same compiler preprocessor


1. handles #include & #define

3. Same built-in operators (+-/*……)

4. Same built-in control structures


1. if, for, while, switch ….

5. Must have a function names “main” to determine where the


program starts

6. Functions are defined the same way

BY ZIA AKBAR 9
differences
in C all code exists in 1. in C++ classes are used to
function and the model the behavior of data
paradigm is that we objects, behavior is
manipulate data with represented by functions and
functions those functions are used to
modify the object’s data
1. in C a struct is used to
make an aggregate type
and cannot have 1. in C++ struct there may be
associated functions associated (part of the
struct) functions to process
the data

BY ZIA AKBAR 10
Contd….

in C I/O is 1. in C++ it is done by


accomplished via using object
library functions methods.(cout,cin)
(printf,scanf..)
C++ has function and
1. in C function operator
names must be overloading
unique. (operators can be
redefined to do
C uses “malloc” and “free” other things)
C++ uses “new” and
“delete” for dynamic
memory management

BY ZIA AKBAR 11
• C does not have any classes or objects. It is procedure and function
driven. There is no concept of access through objects and structures
are the only place where there is a access through.
• C structures have a different behavior compared to c++ structures.
Structures in c do not accept functions as their parts.

• C input/output is based on library and the processes are carried out


by including functions. C++ i/o is made through console commands
cin and cout.

• C functions do not support overloading. Operator overloading is a


process in which the same function has two or more different
behaviours based on the data input by the user.

– C does not support new or delete commands. The memory


operations to free or allocate memory in c are carried out by
malloc() and free().

BY ZIA AKBAR 12
• Undeclared functions in c++ are not allowed. The function has
to have a prototype defined before the main() before use in c++
although in c the functions can be declared at the point of use.

• After declaring structures and enumerators in c we cannot


declare the variable for the structure right after the end of the
structure as in c++.

• For an int main() in c++ we may not write a return statement


but the return is mandatory in c if we are using int main().

• In C++ identifiers are not allowed to contain two or more


consecutive underscores in any position. C identifiers cannot
start with two or more consecutive underscores, but may
contain them in other positions.

BY ZIA AKBAR 13
• C has a top down approach whereas c++ has a bottom up
approach.

• In c a character constant is automatically elevated to an integer


whereas in c++ this is not the case.

• In c declaring the global variable several times is allowed but this


is not allowed in c++.

BY ZIA AKBAR 14
Basic concepts
• Objects

• Classes

• Data abstraction and encapsulation

• Inheritance

• Polymorphism

• Dynamic binding

• Message passing

BY ZIA AKBAR 15
objects
• Objects are the basic run time entities.

• Objects are class variables and use classes data and functions.

• Represents real world things and user defined data like bank
account, any item, any place etc...

• “Object” is an instance of a class. Each object has a class which


defines its data and behavior.

BY ZIA AKBAR 16
Concept: An object has behaviors

• In old style programming, you had:


– data, which was completely passive
– functions, which could manipulate any data
• An object contains both data and methods
that manipulate that data
– An object is active, not passive; it does things
– An object is responsible for its own data
• But: it can expose that data to other objects

BY ZIA AKBAR 17
An object has state
• An object contains both data and methods that
manipulate that data
– The data represent the state of the object
– Data can also describe the relationships between
this object and other objects

• Example: A CheckingAccount might have


– A balance (the internal state of the account)
– An owner (some object representing a person)

BY ZIA AKBAR 18
Example: A “Rabbit” object

• You could (in a game, for example) create


an object representing a rabbit
• It would have data:
– How hungry it is
– How frightened it is
– Where it is
• And methods:
– eat, hide, run, dig

BY ZIA AKBAR 19
Example: A “man” object

• You could (in a game, for example) create an


object representing a man
• It would have data:
– How hungry he is
– How brave he is
– Where he is
• And methods:
– eat, play, run

BY ZIA AKBAR 20
Classes

• Class is a collection of objects.

• Classes contain the entire set of data and code.

• Classes are user defined data type and behave like


built-in data type

BY ZIA AKBAR 21
Concept: Classes describe objects
• Every object belongs to (is an instance of) a class.

• An object may have fields, or variables


– The class describes those fields

• An object may have methods


– The class describes those methods

• Examples: set of birds


» Set of pet animals
» Set of shapes

BY ZIA AKBAR 22
Data abstraction and
encapsulation
• Data abstraction is representing a method of show only essential
features with out including back ground detail.

• Wrapping up of data and function into a single unit (class) is


called encapsulation.
• Only those function who wrapped with the data can access it.
• It provide data hiding by protecting data
from direct access

BY ZIA AKBAR 23
Inheritance
• Process by which object of one class acquire the
properties of another class

Engineers

Civil Mechanical Electronics

Automobile Contd…

BY ZIA AKBAR 24
Contd….

• Inheritance provides idea of reusability.

• We can add additional features to an existing class


without modifying it.

• We can derive new class from an existing class new


class is known as derived class and the existing class is
called base class.

BY ZIA AKBAR 25
Polymorphism
• To take more than one form.

• An operation perform different task with different


instances and behaviors depend on the data types
used in operation.

• Examples : “ +” operator perform addition, with


number it will give a number while with string it will
gives a string by concatenating two strings.

• Polymorphism allow function overloading (many


function with same name) and operator overloading.

BY ZIA AKBAR 26
Example :-

1. We uses three functions with


DRAW same name DRAW ( ) to create
(SQUARE) these shapes.
2. These functions will be called
according to the objects and
executes at run time.
3. Three objects are created for
DRAW different shapes.
( CIRCLE)

DRAW
( TRIANGLE)

BY ZIA AKBAR 27
Binding

• It refers to linking the function call to


the function code.

binding

Early / compile time Dynamic


binding Static Late binding/
binding binding
run time
Call associated with code Function call associated with code
at compile time. at run time.
BY ZIA AKBAR 28
Message passing

• It is a process through which objects are


communicate with each other by sharing information.
• It involves name of object, name of function and
information to be send.
• For example:-
» Student.grade(name);

Object
Function information
name
BY ZIA AKBAR 29
Benefits of OOPs

• Eliminate redundant code and extend reusability of


existing code by inheritance.
• Data hiding helps the programmers to built secure
code.
• Easy partition of work into objects.
• Easily upgraded from small to large systems.
• Software complexity can be easily managed.

BY ZIA AKBAR 30
Object oriented
languages

Object based Object oriented


languages programming languages
1. Supports encapsulation and
object identity. 1. It include all features of
2. Major features required by object object based languages
based languages with two additional
1. Data encapsulation. features that are
2. Data hiding and access inheritance and
mechanisms. dynamic binding
3. Operator overloading 2. Examples :- C++,
4. Automatic initialization and Smalltalk, Java
clear up of objects.
5. Example :-Ada BY ZIA AKBAR 31
» What is c++ ?

1. Developed by Bjarne Stroustrup in 1980’s at AT & T


Bell laboratories.
2. Includes features of simula 67 and C.
3. Superset of c.
4. Initially known as “c with class”.
5. In 1983 the name was changed to “c++”

BY ZIA AKBAR 32
Applications of C++
It is suitable for following programming task
1. development of editors
2. compilers
3. databases
4. communication systems
5. any real life systems

BY ZIA AKBAR 33
General form of a C++ program
• // Program description
• #include directives
• int main()
• {
• constant declarations
• variable declarations
• executable statements
• return 0;
• }
BY ZIA AKBAR 34
C++ statements
• #include<iostraem.h>
• Int main()
• { float num 1,num2,sum,avg;
– Cout<<“enter two numbers:”;
– Cin>>num1;
– Cin>>num2;
– sum=num1+num2;
– Avg=sum/2;
– Cout<<“sum”= <<sum <<“\n”;
– Cout<<“average”= <<avg <<“\n”;
– Return 0;
}
BY ZIA AKBAR 35
Iostream
it add the contents of the iostream file to the prroogram. The
iostream contains the declarations of COUT and << operator.
In old versions of compiler iostream.h header file is used.

Math.h Contains function prototype for


math library function
Stdio.h Contain function prototype for
input/output library functions and
its information
String.h Contain function prototype for c-
style string processing functions.
Iostream.h Contain function prototypes for the
standard input/output functions.

Stdlib.h Contain function prototype for text


to number and number to text
conversion, memmory allocation.
BY ZIA AKBAR 36
• Cin is predefined object in c++ that
corresponds to the standard input
stream(key borad).
• The >> operator is known as extraction
or get from operator.
• It takes value from keyborad and
assign to the right side variable.

BY ZIA AKBAR 37
• Cout is predefined object in c++ that
corresponds to the standard output
stream(moniter).
• The <<operator is known as insertion
operator.
• It dispaly value in to moniter and assign
it to cout.

BY ZIA AKBAR 38
Structure of c++ program

1. Include header files


2. Class declaration
3. Member functions definitions
4. Main function

BY ZIA AKBAR 39
Class name • C++ program with classes

#include<iostream.h> Void employee::show()


Class employee {
{ cout<<“\nname”<<name;
Int e_id; cout<<“\n age” << age;
char name[30]; }
Class int age; Data Int main()
defnition public: {
void getdata(); Employee rohit,; Member
void show(); rohit.getdata(); function
}; rohit.show();
Void employee::getdata() Return 0;
{ } main
Member cout<<“enter name” <<“enter
Function age”;
defnition cin>>name >>age; Object declaration
Function
} {class name +
/member
function Object name}
declaration
Function calling by using
BY ZIA AKBAR 40
Class name • C++ program with classes

#include<iostream.h> Void show()


Class employee {
{ cout<<“\nname”<<name;
Int e_id; cout<<“\n age” << age;
char name[30]; }
Class int age; Data };
defnition public: Int main()
void getdata() { Member
{ Employee rohit,;function
cout<<“enter name” <<“enter age”; rohit.getdata();
cin>>name >>age; rohit.show();
} Return 0; main
Member }
Function
defnition Function Object declaration
/member {class name +
function Object name}
declaration
Function calling by using
BY ZIA AKBAR 41
• The data members of any class is the
showing the attributes of the objects of
its class and member function shows
the behavior of its class objects.
• In the last slide the name and age data
members are the attributes of the object
F1 and getdata and show member
functions are the behavior of F1.

BY ZIA AKBAR 42
The Operators new and delete
• The unary operators new and delete are available to
manipulate free store.
• They are more convenient than the C functions
malloc(), calloc(), and free().
• Free store is a system-provided memory pool for
objects whose lifetime is directly managed by the
programmer.
• This adds responsibility to the programmer and can
easily lead to problems such as memory leaks.
• On the other hand, manipulating free store is an
efficient and flexible way to handle data structures
such as trees and lists.
BY ZIA AKBAR 43
The Operators new and delete
• The programmer creates an object using new, and destroys
the object using delete.
• The operator new is typically used in the following forms:
– new type-name
– new type-name initializer
– new type-name [expression]
• In each case, there are at least two effects:
– An appropriate amount of store is allocated from
free store to contain the named type.
– The base address of the object is returned as
the value of the new expression.

BY ZIA AKBAR 44
The Operators new and delete
• Example:
• …
• int *p, *q;
• p = new int(5);
• q = new int[10];
• …

• In this code,
• the pointer variable p is assigned the address of the store
obtained,
• The location pointed at by p is initialized to the value 5,
• the pointer variable q is assigned the base address of an int
array of size 10.
BY ZIA AKBAR 45
The Operators new and delete
• Notice the following things:
• When memory is unavailable, the operator new can
either throw a bad_alloc exception or return the value
0.
• If no initializer is provided, the content of the
allocated memory is undefined.
• Arrays cannot be initialized using the new operator.
• Objects created by the new operator always need to
be destroyed by the delete operator as soon as they
are not used by the program any more.

BY ZIA AKBAR 46
The Operators new and delete
• The operator delete destroys an object created by new.
• This returns its allocated storage to free store for reuse.
• The operator delete is used in the following forms:
– delete expression
– delete [] expression
• The first form is used when the corresponding new expression
has not allocated an array.
• The second form (empty brackets) is used when the original
allocation was an array.
• The return type of delete is void (no return value).

BY ZIA AKBAR 47
The Operators new and delete
• Example: Dynamic allocation of an array
• int main() Starting the program:
• {
• int *data; Enter array size: 4
• int size; 0
• cout << “\nEnter array size: “; 1
2
• cin >> size; 3
• data = new int[size];
• for (int j = 0; j < size; j++)
• cout << (data[j] = j) << ‘\n’;
• delete [] data;
• return 0;
• }

BY ZIA AKBAR 48
BY ZIA AKBAR 49
CLASS & OBJECT
UNIT 2

BY ZIA AKBAR 50
• Class: A Class is a user defined data type
to implement an abstract object. Abstract
means to hide the details. A Class is a
combination of data and functions.

• Data is called as data members and


functions are called as member functions.

BY ZIA AKBAR 51
• A class definition begins with the
keyword class.
• The body of the class is contained
within a set of braces, { } ; (notice the
semi-colon).
class class_name Any valid
{ identifier
….
….
Class body (data member +
….
methods)
methods
};

BY ZIA AKBAR 52
• Within the body, the keywords private:
and public: specify the access level of
the members of the class.
– the default is private.

• Usually, the data members of a class


are declared in the private: section of
the class and the member functions
are in public: section.
BY ZIA AKBAR 53
• Data member or member functions may be
public, private or protected.

• Public means data members or member


functions defining inside the class can be used
at outside the class.( in different class and in
main function)

• Member access specifiers


– public:
• can be accessed outside the class directly.
– The public stuff is the interface.
– main function).

BY ZIA AKBAR 54
– private:
• Accessible only to member functions of class
• Private members and methods are for internal
use only.

• Private means data members and member


functions can’t be used outside the class.

• Protected means data member and member


functions can be used in the same class and
its derived class (at one level) (not in
BY ZIA AKBAR 55
PRIVATE

PUBLIC

BY ZIA AKBAR 56
class class_name
{
private: private members or
… methods


public:
… Public members or methods


};

BY ZIA AKBAR 57
• This class example shows how we can
encapsulate (gather) a circle
information into one package
No need(unit
for othersor
classes to
class)
class Circle access and retrieve its value directly.
The
{
class methods are responsible for
private: that only.
double radius;
public:
void setRadius(double r); double They are accessible from outside
getDiameter(); the class, and they can access the
double getArea(); member (radius)
double getCircumference();
};
BY ZIA AKBAR 58
Class Example (Problem)
#include<iostream.h> void main()
#include<stdio.h> {
class student student s;
{ cout<<“enter the rollno.:”;
int rollno; cin>>s.rollno;
char name[20]; cout<<“enter the name:”;
}; gets(s.name);
cout<<“rollno:”<<s.rollno;
cout<<“\nname:”;
puts(s.name);
}
BY ZIA AKBAR 59
Class Example (Solution)
#include<iostream.h> void main()
#include<stdio.h> {
class student student s;
{ cout<<“enter the rollno.:”;
public: cin>>s.rollno;
int rollno; cout<<“enter the name:”;
char name[20]; gets(s.name);
}; cout<<“rollno:”<<s.rollno;
cout<<“\nname:”;
puts(s.name);
}
BY ZIA AKBAR 60
Implementing class
methods
• There are two ways:
1. Member functions defined outside class
• Using Binary scope resolution operator (::)
• “Ties” member name to class name
• Uniquely identify functions of particular class
• Different classes can have member functions with
same name
– Format for defining member functions
ReturnType ClassName::MemberFunctionName( ){

}

BY ZIA AKBAR 61
Member Function
Defining Inside the Class
#include<iostream.h>
#include<stdio.h>
class student
{ Data Members (Private : in this example)
int rollno;
char name[20];
public:
void getdata()
{
cout<<“enter the rollno.:”; Member Functions (Public: in this example)
cin>>rollno;
cout<<“enter the name:”;
gets(name);
}
void putdata()
{
cout<<“rollno:”<<rollno;
cout<<“\nname:”;
puts(name);
}
}; Calling member function
void main()
{
student s;
s.getdata();
s.putdata();
}
BY ZIA AKBAR 62
#include<iostream.h>Member Function
#include<stdio.h>Defining Outside the Class
class student void student: :: putdata()
{ {
int rollno; cout<<“rollno:”<<rollno;
char name[20]; cout<<“\nname:”;
public: puts(name);
void getdata(); }
void putdata(); void main()
}; {
void student :: getdata() student s,s1;
{ S1=s;
cout<<“enter the rollno.:”;s.getdata();
cin>>rollno; s.putdata();
cout<<“enter the name:”;}
gets(name); BY ZIA AKBAR 63
}
Characteristics of member
function
• Different classes have same function name. the
“membership label” will resolve their scope.
• Member functions can access the private data of
the class .a non member function cannot do this.
(friend function can do this.)
• A member function can call another member
function directly, without using the dot operator.

BY ZIA AKBAR 64
Accessing Class Members
• Operators to access class members
– Identical to those for structs
– Dot member selection operator (.)
• Object
• Reference to object
– Arrow member selection operator (->)
• Pointers

BY ZIA AKBAR 65
Creating an object of a
Class
• Declaring a variable of a class type creates an
object. You can have many variables of the
same type (class).
– Instantiation
• Once an object of a certain class is
instantiated, a new memory location is
created for it to store its data members and
code
• You can instantiate many objects from a class
type.
– Ex) Circle c; Circle *c;
BY ZIA AKBAR 66
Memory Allocation of
Object
class student
{ rollno – 2 bytes

int rollno;
char name[20]; name- 20 bytes

int marks;
};
marks- 2 bytes
student s;

24 bytes s
BY ZIA AKBAR 67
Array of objects
• An array can be of data type including struct an
class .
• The array of class type variable is known as array
of object.
• We can declare array of object as following way:-
Class _name object [length];
Employee manager[3];
1. We can use this array when calling a member function
2. Manager[i].put data();
3. The array of object is stored in memory as a multi-
dimensional array. BY ZIA AKBAR 68
Object as function
arguments
• This can be done in two ways:-

• A copy of entire object is passed to the function.


• ( pass by value)

• Only the address of the object is transferred to


the function. (pass by reference)

BY ZIA AKBAR 69
( pass by value)
• A copy of the object is passed to the function,
any changes made to the object inside the
function do not affect the object used to call
function.

(pass by reference)

• When an address of object is passed, the called


function works directly on the actual object used
in the call. Means that any change made in side
the function will reflect in the actual object.
BY ZIA AKBAR 70
#include<iostream.h>
class Complex
Passing Object
{
float real, imag;
public: void Complex : : sum ( complex A, complex B)
void getdata( ); {
void putdata( ); real = A.real + B.real;
void sum (Complex A, Complex imag= A.imag + B.imag;
B);
}; }
void Complex : : getdata( )
{ void main( )
cout<<“enter real part:”; {
cin>>real;
Complex X,Y,Z;
cout<<“enter imaginary part:”;
cin>>imag; X.getdata( );
} Y.getdata( );
void Complex : : putdata( ) Z.sum(x,y);
{ Z.putdata( );
if (imag>=0)
}
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”; BY ZIA AKBAR 71
}
Passing Object
#include<iostream.h>
class Complex void Complex : : sum ( Complex A, Complex B)
{ {
float real, imag; real = A.real + B.real;
public:
void getdata( ); imag= A.imag + B.imag;
void putdata( ); }
void sum (Complex A, Complex B);
};
void Complex : : getdata( ) void main( )
{ {
cout<<“enter real part:”;
cin>>real; Complex X,Y,Z;
cout<<“enter imaginary part:”; X.getdata( );
cin>>imag;
Y.getdata( );
} X Y Z
void Complex : : putdata( ) Z.sum(X,Y);
{ Z.putdata( );
if (imag>=0)
cout<<real<<“+”<<imag<<“i”; }
else
cout<<real<<imag<<“i”;
}

BY ZIA AKBAR 72
Passing Object
#include<iostream.h>
class Complex void Complex : : sum ( Complex A, Complex B)
{ {
float real, imag; real = A.real + B.real;
public:
void getdata( ); imag= A.imag + B.imag;
void putdata( ); }
void sum (Complex A, Complex B);
};
void Complex : : getdata( ) void main( )
{ {
cout<<“enter real part:”;
cin>>real; Complex X,Y,Z; 5 7
cout<<“enter imaginary part:”; X.getdata( ); 6 8
cin>>imag;
Y.getdata( );
} X Y Z
void Complex : : putdata( ) Z.sum(X,Y);
{ Z.putdata( );
if (imag>=0)
cout<<real<<“+”<<imag<<“i”; }
else
cout<<real<<imag<<“i”;
}

BY ZIA AKBAR 73
Passing Object
#include<iostream.h>
class Complex void Complex : : sum ( Complex A, Complex B)
{ {
float real, imag; real = A.real + B.real;
public:
void getdata( ); imag= A.imag + B.imag;
void putdata( ); }
void sum (Complex A, Complex B);
};
void Complex : : getdata( ) void main( )
{ {
cout<<“enter real part:”;
cin>>real; Complex X,Y,Z; 5 7
cout<<“enter imaginary part:”; X.getdata( ); 6 8
cin>>imag;
Y.getdata( );
} X Y Z
void Complex : : putdata( ) Z.sum(X,Y);
{ Z.putdata( );
if (imag>=0) 5 7
cout<<real<<“+”<<imag<<“i”; }
6 8
else
cout<<real<<imag<<“i”;
} A B

BY ZIA AKBAR 74
Passing Object
#include<iostream.h>
class Complex void Complex : : sum ( Complex A, Complex B)
{ {
float real, imag; real = A.real + B.real;
public:
void getdata( ); imag= A.imag + B.imag;
void putdata( ); }
void sum(Complex A, Complex B);
};
void Complex : : getdata( ) void main( )
{ {
cout<<“enter real part:”;
cin>>real; Complex X,Y,Z; 5 7 12
cout<<“enter imaginary part:”; X.getdata( ); 6 8 14
cin>>imag;
Y.getdata( );
} X Y Z
void Complex : : putdata( ) Z.sum(X,Y);
{ Z.putdata( );
if (imag>=0) 5 + 7 =
cout<<real<<“+”<<imag<<“i”; }
6 + 8 =
else
cout<<real<<imag<<“i”;
} A B

BY ZIA AKBAR 75
Passing Object
#include<iostream.h> void complex : : sum ( Complex A, Complex B)
class Complex {
{ real = A.real + B.real;
float real, imag; imag= A.imag + B.imag;
public: }
void getdata( );
void putdata( ); void main( )
void sum (Complex A, Complex B); {
}; Complex X,Y,Z;
void Complex : : getdata( ) X.getdata( );
{ Y.getdata( );
cout<<“enter real part:”;
cin>>real;
Z.sum(X,Y); 5 7 12
Z.putdata( );
cout<<“enter imaginary part:”; 6 8 14
}
cin>>imag;
} X Y Z
void Complex : : putdata( )
{
if (imag>=0) 12 + 14 i 5 + 7 =
cout<<real<<“+”<<imag<<“i”; 6 8
else + =
cout<<real<<imag<<“i”;
} A B

BY ZIA AKBAR 76
#include<iostream.h>
class Complex
{
float real, imag; Returning Object
Complex Complex : : sum (Complex
public:
B)
void getdata( );
{
void putdata( );
Complex temp;
Complex sum (Complex B);
temp.real=real + B.real;
};
temp.imag= imag + B.imag;
void Complex : : getdata( )
return temp;
{
}
cout<<“enter real part:”;
void main ( )
cin>>real;
{
cout<<“enter imaginary part:”;
Complex X, Y, Z;
cin>>imag;
X.Getdata( );
}
Y. getdata( );
void Complex : : putdata( )
Z= X.sum (Y);
{
Z.putdata( );
if (imag>=0)
}
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”; BY ZIA AKBAR 77
}
#include<iostream.h>
Returning Object
Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( )
{
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}

BY ZIA AKBAR 78
#include<iostream.h>
Returning Object
Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{
if (imag>=0) 6 8
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}

BY ZIA AKBAR 79
#include<iostream.h>
Returning Object
Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{
if (imag>=0) 6 8
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}
7
8
BY ZIA AKBAR 80
B
#include<iostream.h>
Returning Object
Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{
if (imag>=0) 6 8
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}
7
8
BY ZIA AKBAR 81
B
#include<iostream.h>
Returning Object
Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{
if (imag>=0) 6 8
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}
7 12
8 14
BY ZIA AKBAR 82
B temp
#include<iostream.h>
Returning Object
Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{
if (imag>=0) 6 8
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}
7 12
8 14
BY ZIA AKBAR 83
B temp
#include<iostream.h>
Returning Object
Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7 12
{
if (imag>=0) 6 8 14
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}
7 12
8 14
BY ZIA AKBAR 84
B temp
#include<iostream.h>
Returning Object
Complex Complex : : sum (Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=real + B.real;
public: temp.imag= imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
Complex sum (Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= X.sum (Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7 12
{
if (imag>=0) 6 8 14
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}
12 + 14 i 7 12
8 14
BY ZIA AKBAR 85
B temp
Friend function
• C++ allows a way through which a function can
access the private data of a class.

• Such a function need not be a class member, it


may be member function of another class or
may be non member function.

• This function is called FRIEND FUNCTION. The


declaration should be preceded by keyword
FRIEND.
BY ZIA AKBAR 86
• The function is defined
Class PQr
elsewhere in the program like
{ normal function.
Private:
………
• Function definition does not
Public:
use either keyword FRIEND or
……
scope operator.
……
Friend void abc();
}; • Functions that are declared
with FRIEND keyword are
known
BY ZIA as friend functions.
AKBAR 87
• A function can declared as friend in number of
class.

• A friend function has full access right to access


the private members of class.

• Member function of one class can be friend of


another class.

BY ZIA AKBAR 88
Characteristics
• It is not in the scope of the class in which it has
been declared as friend.
• it is not in the scope of class so it cannot be
called using object of that class.
• It can be invoked like normal function ,without
object.

BY ZIA AKBAR 89
• It can be declared either in public or private part
with out affecting its meaning.

• Usually, it has the objects as arguments.

• Unlike member function, it cannot access the


member names directly and has to use an object
name and dot membership operator with each
name. like
– A.h
BY ZIA AKBAR 90
#include<iostream.h>
class Complex
{

Friend Function
float real, imag; Complex sum (Complex A, Complex B)
public: {
void getdata( ); Complex temp;
Friend void putdata( complex ); temp.real=A.real + B.real;
friend Complex sum (Complex A, Complex B); temp.imag= A.imag + B.imag;
}; return temp;
void Complex : : getdata( ) }
{ void main ( )
cout<<“enter real part:”; {
cin>>real; Complex X, Y, Z;
cout<<“enter imaginary part:”; X.getdata( );
cin>>imag; Y. getdata( );
} Z= sum (X,Y);
void putdata(complex s ) putdata(Z );
{ }
if (s.imag>=0)
cout<<s.real<<“+”<<s.imag<<“i”;
else
cout<<s.real<<s.imag<<“i”;
}

BY ZIA AKBAR 91
#include<iostream.h>
Friend Function Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( )
{
if (imag>=0)
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}

BY ZIA AKBAR 92
#include<iostream.h>
Friend Function Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{
if (imag>=0) 6 8
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}

BY ZIA AKBAR 93
#include<iostream.h>
Friend Function Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{
if (imag>=0) 6 8
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}
5 7
6 8
BY ZIA AKBAR 94
A B
#include<iostream.h>
Friend Function Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{
if (imag>=0) 6 8
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}
5 + 7 =
6 + 8 =
BY ZIA AKBAR 95
A B temp
#include<iostream.h>
Friend Function Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7
{
if (imag>=0) 6 8
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}
5 + 7 = 12
6 + 8 = 14
BY ZIA AKBAR 96
A B temp
#include<iostream.h>
Friend Function Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7 12
{
if (imag>=0) 6 8 14
cout<<real<<“+”<<imag<<“i”;
else
cout<<real<<imag<<“i”;
X Y Z
}
5 + 7 = 12
6 + 8 = 14
BY ZIA AKBAR 97
A B temp
#include<iostream.h>
Friend Function Complex sum (Complex A, Complex B)
class Complex {
{ Complex temp;
float real, imag; temp.real=A.real + B.real;
public: temp.imag= A.imag + B.imag;
void getdata( ); return temp;
void putdata( ); }
friend Complex sum (Complex A, Complex B); void main ( )
}; {
void Complex : : getdata( ) Complex X, Y, Z;
{ X.Getdata( );
cout<<“enter real part:”; Y. getdata( );
cin>>real; Z= sum (X,Y);
cout<<“enter imaginary part:”; Z.putdata( );
cin>>imag; }
}
void Complex : : putdata( ) 5 7 12
{
if (imag>=0) 6 8 14
cout<<real<<“+”<<imag<<“i”; 12 + 14 i
else
cout<<real<<imag<<“i”;
X Y Z
}
5 + 7 = 12
6 + 8 = 14
BY ZIA AKBAR 98
A B temp
• We can also declare all the member functions of
one class as the friend functions of another
class. In this case the first class is known as
FRIEND class.

• This can be specified as follows :-


Class z
{
…………..
……
Friend class x;
}; BY ZIA AKBAR 99
#include<iostream.h>
Class ABC;
Class XYZ
{ int x;
Int main ()
Public:
{
Void setvalue(ABC);
ABC abc;
};
abc..showvalue(10);
Void XYZ::setvalue(ABC A)
XYZ xyz;
{ x=A.a ;
xyz.Setvalue(abc);
Cout<<“value of x”<<x;
Return 0;
}
}
Class ABC
{ int a;
Public:
void showvalue(int i)
{ a=i ;
Cout<<“value of a”<<a;}
Friend class XYZ;
};

BY ZIA AKBAR 100


Createing A member function
a class as a friend function
of
#include<iostream.h>
another class
Void ABC ::max(XYZ m,)
Class XYZ; {
Class ABC If(m.x>=m.y)
{ Cout<<m.x;
Public: Else
void max(XYZ); Cout<<m.y;
}; }
Class XYZ Int main ()
{ int x,y; {XYZ xyz;
Public: ABC abc;
Void setvalue(int i,int j) xyz.setvalue(10,20);
{ x=i ; y=j;} abc.max(xyz);
Friend void ABC ::max(XYZ); Return 0;
}; }

BY ZIA AKBAR 101


A function friend in two
#include<iostream.h>
classes
Void max(XYZ m,ABC n)
Class ABC; {
Class XYZ If(m.x>=n.a)
Cout<<m.x;
{ int x;
Else
Public:
Cout<<n.a;
Void setvalue(int i)
}
{ x=i ; }
Int main ()
Friend void max(XYZ,ABC);
{
};
ABC abc;
Class ABC
abc..setvalue(10);
{ int a;
XYZ xyz;
Public:
Xyz.setvalue(20);
void setvalue(int i)
max(xyz,abc);
{ a=i ;}
Return 0;
Friend void max(XYZ,ABC);
}
}; BY ZIA AKBAR 102
Pass by reference
#include<iostream.h> Class class_2
Class class_2; { int value2;
Class class_1 public:
{ int value1; void indata( int a)
Public: { value2=a; }
void indata(int a) Void display()
{ value1=a; } { cout<<value2<<“\n”; }
Void display() Friend void exchange(class_1 &,
{ cout<<value1<<“\n”; } class_2 &);
Friend void exchange(class_1 &, };
class_2 &);
}; Contd…
BY ZIA AKBAR 103
Void exchange(class_1 & x, C1.indata(100);
class_2 & y) C2.indata(200);
{ int temp=x.value1; Cout<<“values before exchange”
x.value1=y.value2; <<“\n”;
y.value2=temp; C1.dispaly();
} C2.display();
Int main() Exchange(c1,c2);
{ Cout<<“values after exchange”
class_1 c1; <<“\n”;
Class_2 c2; C1.display();
C2.display();
Return 0;
} AKBAR
BY ZIA 104
INLINE FUNCTION

BY ZIA AKBAR 105


INTRODU
CTION
• In C, we have used Macro function an
optimized technique used by compiler to
reduce the execution time etc.

• Inline function is introduced which is an


optimization technique used by the compilers
especially to reduce the execution time. We
will cover “what, why, when & how” of inline
functions.
BY ZIA AKBAR 106
What is inline
function
The inline functions: are a C++ enhancement
feature to increase the execution time of a
program.
Functions can be instructed to compiler to
make them inline so that compiler can replace
those function definition wherever those are
being called.
Compiler replaces the definition of inline
functions at compile time instead of referring
function definition at runtime.

if function is big (in term of executable


instruction etc) then, compiler
BY ZIA AKBAR
can ignore the 107
“inline” request and treat the function as normal
How to make
function inline:
• To make any function as inline, start its
definitions with the keyword “inline”.

inline int add(int a, int b)


{
return (a + b);
};

BY ZIA AKBAR 108


Why to
• Inuse
many-places we create the functions for
small work/functionality which contain simple
and less number of executable instruction.
Imagine their calling overhead each time they
are being called by callers.

When a normal function call instruction is
encountered, the program stores the memory
address of the instructions immediately
following the function call statement, loads
the function being called into the memory,
copies argument values, jumps to the memory
location of the called function, executes the
function codes, stores the return value of the
function, and then jumpsBY ZIAback
AKBAR to the address 109

of the instruction that was saved just before


• The C++ inline function provides an alternative.

• With inline keyword, the compiler replaces the


function call statement with the function code
itself (process called expansion) and then
compiles the entire code.

• Thus, with inline functions, the compiler does


not have to jump to another location to
execute the function, and then jump back as
the code of the called function is already
available to the calling program.
BY ZIA AKBAR 110
Pro
1.sIt speeds
- up your program by avoiding function
calling overhead.

2. It save overhead of variables push/pop on the


stack, when function calling happens.
3. It save overhead of return call from a function.

4. It increases locality of reference by utilizing


instruction cache.

5. By marking it as inline, you can put a function


definition in a header fileBY ZIA
(i.e. it
AKBAR
can be included in111
multiple compilation unit, without the linker
Con
sexpansion.
-
1. It increases the executable size due to code

2. C++ inlining is resolved at compile time. Which


means if you change the code of the inline
function, you would need to recompile all the code
using it to make sure it will be updated
3. When used in a header, it makes your header file
larger with information which users don’t care.
4. As mentioned above it increases the executable
size, which may cause thrashing in memory. More
number of page fault bringing down your program
performance.
5. Sometimes not useful for example in embedded
BY ZIA AKBAR 112

system where large executable size is not


When to
use -
Function can be made as inline as per
programmer need. Some useful
recommendation are mentioned below-

1.Use inline function when performance is


needed.
2.Use inline function over macros.
3.Prefer to use inline keyword outside the class
with the function definition to hide
implementation details.
BY ZIA AKBAR 113
Key
Points -
1.It’s just a suggestion not compulsion. Compiler may or
may not inline the functions you marked as inline. It may
also decide to inline functions not marked as inline at
compilation or linking time.
2.Inline works like a copy/paste controlled by the
compiler, which is quite different from a pre-processor
macro: The macro will be forcibly inlined, will pollute all
the namespaces and code, won't be easy to debug.
3.All the member function declared and defined within
class are Inline by default.
So no need to define explicitly.
4.Virtual methods are not supposed to be inlinable. Still,
sometimes, when the compiler can know for sure the
type of the object (i.e. the object was declared and
constructed inside the sameBYfunction
ZIA AKBAR
body), even a 114
virtual function will be inlined because the compiler
knows exactly the type of the object.
• 5. Template methods/functions are not always
inlined (their presence in an header will not
make them automatically inline).

6. Most of the compiler would do in-lining for


recursive functions but some compiler
provides #pragmas-
microsoft c++ compiler - inline_recursion(on)
and once can also control its limit with
inline_depth.
In gcc, you can also pass this in from the
command-line with --max- inline-insns-
recursive
BY ZIA AKBAR 115
Program
code-
#include <iostream>
using namespace
std;
inline int sqr(int x) output: ans is 9
{
int y;
y = x * x;
return y;
}
int main()
{
int a =3, b;
b = sqr(a);
cout <<"ans is "<<b;
return 0;
}

BY ZIA AKBAR 116


Constructors

and

Destructors

BY ZIA AKBAR 117



Constructor
It is a member function which initializes
the objects of its class.

• A constructor has:
(i) the same name as the class itself
(ii) no return type ,not even void.

• It constructs the values of data member


so that it is called constructor.
BY ZIA AKBAR 118
A constructor is called automatically
whenever a new object of a class is
created.

You must supply the arguments to


the constructor when a new object is
created.

If you do not specify a constructor,


the compiler generates a default
constructor for you (expects no
parameters and has
BY ZIA AKBAR an empty body).
119
void main()
{
rectangle rc(3.0, 2.0);

rc.posn(100, 100);
rc.draw();
rc.move(50, 50);
rc.draw();
}

• Warning: attempting to initialize a data


member of a class explicitly in the class
definition is a syntax error.

BY ZIA AKBAR 120


Declaration and defination
Class complex
{
Int m,n;
Public:
complex();
};
complex :: complex ()
{
m=0;n=0;
} BY ZIA AKBAR 121
• A constructor that accepts no
parameters is called default
constructor.

BY ZIA AKBAR 122


characteristics
1. They should be declared in public
section.
2. Invoked automatically when class
objects are created.
3. They do not have return types, not
even void and they can't return any
value.
4. They cannot be inherited,though a
derived class canBYcall the base class
ZIA AKBAR 123
5. They have also default arguments like
other functions.
6. They implicitly call the NEW and
DELETE operators when memory
allocation is required.
7. Constructors can not be virtual.

BY ZIA AKBAR 124


Types of Constructor
• Default Constructor
• Parameterize Constructor
• Copy Constructor
• C++ Default Constructor
– Construct without parameter is called
default constructor. Example of C++
default constructor

BY ZIA AKBAR 125


• #include<iostream.h> #include<string.h>
• class Student {
• int Roll; char Name[25]; float Marks;
• public:
• Student() //Default Constructor
• { Roll = 1;
• strcpy(Name,"Kumar");
• Marks = 78.42; }
• void Display() { cout<<"\n\tRoll : "<<Roll; cout<<"\n\tName : "
<<Name; cout<<"\n\tMarks : "<<Marks; } };
• void main() {
• Student S; //Creating Object
• S.Display(); //Displaying Student Details
• }


• Output :
• Roll : 1 Name : Kumar Marks : 78.42

BY ZIA AKBAR 126
Parameterized
constructors
• The constructors that can take
arguments are called parameterized
constructors.

• It is used when we assign different value


to the data member for different object.

• We must pass the initial values as


arguments to the constructors when an
object is declared.
BY ZIA AKBAR 127
• This can be done in two ways:-
– By calling the constructors implicitly
• Class_name object(arguments);
• Ex:- simple s(3,67);
• This method also known as shorthand.
– By calling the constructors explicitly
• Class_name object =constructor(arguments);
• Ex:- simple s=simple(2,67);
• This statement create object s and passes the
values 2 and 67 to it.
BY ZIA AKBAR 128
Example:-
#include<iostream.h> Int main()
Class integer {
{ int m,n; Integer i1(10,100);
public: Integer i2=integer(33,55);
integer(int,int); Cout<<“object 1”;
void display() i1.display();
{ cout<<“m”<<m; Cout<<“object 2”;
cout<<“n”<<n;} i2.display();
}; Return 0;
Integer::integer(int x,int y) }
{
m=x;
n=y;
BY ZIA AKBAR 129
}
• #include<iostream.h> #include<conio.h> #include<string.h>

• class Student {

• int Roll; char Name[25]; float Marks;

• public:

• Student(int r,char nm[],float m) //Parameterize Constructor { Roll
= r; strcpy(Name,nm); Marks = m; }

• void Display() { cout<<"\n\tRoll : "<<Roll; cout<<"\n\tName : "<<Name;
cout<<"\n\tMarks : "<<Marks; } };


• void main() {

• Student S(2,"Sumit",89.63); //Creating Object and passing values to
Constructor

• • Output :

• S.Display(); //Displaying Student Details
• Roll : 2 Name : Sumit Marks :
• 89.63
• } BY ZIA AKBAR 130
Notes:-

• A constructor function • Parameters of a


can also be defined as constructor can be of
INLINE function. any type except that of
the class to which it
Class integer belongs.
{ int m,n; Class A
public: {
integer (int x,int y) ……….
{ m=x;
…….
n=y;
}};
Public:
A(A);
}; is illegal
BY ZIA AKBAR 131
• A class can accept a • In this case the
reference of its own constructor is
class as parameter.
called as copy
constructor.
Class A
{
………
……………
Public:
A(A&);
};
is valid

BY ZIA AKBAR 132


Copy constructor
• When a class reference is passed as
parameters in constructor then that
constructor is called copy constructor.
• A copy constructor is used to declare and
initialize an object from another object.
• Synatx:-
– Constructor _name (class_name & object);
– Integer (integer &i);

BY ZIA AKBAR 133


– Integer i2(i1);/integer i2=i1;
– Define object i2 and initialize it with i1.
– The process of initialization object through copy
constructor is known as copy initialization.

• A copy constructor takes a reference to an


object of the same class as itself as
argument.

BY ZIA AKBAR 134


• #include<iostream.h> int main()
Class person {
{ public: Person timmy(10);
int age; Person sally(15);
Person(int a) Person timmy_clone = timmy;
{ age = a; } cout << timmy.age << " " <<
Person(person & x) sally.age << " " <<
{ age=x.age; timmy_clone.age << endl;
timmy.age = 23;
}
cout << timmy.age << " " <<
}; sally.age << " " <<
timmy_clone.age << endl;
}

BY ZIA AKBAR 135


• #include<iostream.h> #include<conio.h>
#include<string.h>

• class Student { • Student S2(S1); //Statement 1
• •
• int Roll; char Name[25]; float Marks; • cout<<"\n\tValues in object S1";
• S1.Display();
• public: •
• //Constructor 1 : Parameterize Constructor • cout<<"\n\tValues in object S2";
Student(int r,char nm[],float m) S2.Display();
• { Roll = r; strcpy(Name,nm); Marks = m; •
} • }
• //Constructor 2 : Copy Constructor •
Student(Student &S) •
• { Roll = S.Roll; strcpy(Name,S.Name);
Marks = S.Marks; } • Output :
• •
• void Display() { cout<<"\n\tRoll : "<<Roll; • Values in object S1 Roll : 2 Name :
cout<<"\n\tName : "<<Name; cout<<" Sumit Marks : 89.63
\n\tMarks : "<<Marks; } }; •
• • Values in object S2 Roll : 2 Name :
• Sumit Marks : 89.63
• void main() {

• Student S1(2,"Sumit",89.63);

BY ZIA AKBAR 136


Dynamic constructors
• Constructors can also be used to allocate
memory while creating objects.
• This will allocate the right amount for
each object when the objects are not of
the same size.
• Allocation of memory to objects at the
time of their construction is known as
“dynamic construction of objects”.
• The memory is allocated by NEW operator.

BY ZIA AKBAR 137


#include<iostream.h>
#include<string.h> void join (string &a,string & b);
Class string };
{ void string:: join(striing&a,string &b)
char *name; { length =a.length+b.length;
int length; delete name;
Public: name =new char [length+1];
string() strcpy(name,a.name);
{ strcpy(name,b.name); strcat(name,b.name);
length =0; }
name = newchar[length+1]; Int main()
} { char *first =“jon”;
string(char *s) string name1(first),name2(tom),name3(jery),s1,s2;
{ s1.join(name1.name2);
length=strlen(s); s2.join(s1,name3);
name=new char [length+1]; name1.display();
strcpy(name,s ); name2.display();
} name3.display();
Void display() s1.display();
{ cout<<name<<“\n”;} s2.display();
return 0;
}

BY ZIA AKBAR 138


Constructor overloading
{multiple constructor in a class}
• When more than one function is defined
in a class , is known as constructor
overloading.
• Example:-
Class integer
{ int m,n;
public:
integer()
{ m=0; n=0; }
Integer (int a,int b)
{ m=a;n=b }
Integer(integer&i)
{ m=i.m; BY ZIA AKBAR 139
#include<iostream.h> Void display(complex d)
Class complex { cout<<c.real<<“+j”<<c.imag;
{ float real,imag; }
public: Int main()
complex(){ } {
complex(float x) complex a(3.4,6.7);
{ real=imag=x;} complexb(2.5);
complex(float c, float d) complex c;
{ real=c; imag = d; } c= sum(a,b);
friend complex sum (complex,complex); cou<<“a=”;display(a);
friend display(complex); cout<<“b=”;display(b);
}; cout<<“c=”;display(c);
Complex sum (complex c1, complex c2) }
{ complex c3;
c3.real =c1.real +c2.real;
c3.imag=c1.imag+c2.imag;
Return(c3);
}

BY ZIA AKBAR 140


• Constructors are also define with default
arguments

• Complex (float real ,float imag=0);

• It will invoke by following way complex c(5),


this statement assign 5 to real and the
default value already assigned to imag.

• We can also invoke it like complex(5,3.4),it


will assign values both real and imag means
overwrite the new value to imag value.
BY ZIA AKBAR 141
• More than one constructor with different
signature in a class is called function
overloading. Signature of constructor includes :
• Number of arguments
• Type of arguments
• Sequence of arguments
• When we create an object, the compiler
determines the most appropriate constructor
to use by comparing the signature of the
statement which is creating object with the
signature of specific constructor definition.

BY ZIA AKBAR 142


#include<iostream.h>
#include<conio.h> void main()
#include<string.h> {
Student S1(101,"Kumar",78.53); //
class Student { Statement 1
int Roll; Student S2("Sumit",102,89.27); //
char Name; Statement 2
float Marks; Student S3(103,67.38,"Kunal"); //
public: Statement 3
Student(int r,char nm[],float mks) // S1.Display();
Constructor 1 S2.Display();
{ Roll = r; S3.Display();
strcpy(Name , nm); }
Marks = mks; } Output :
Student(int r,float mks,char nm[]) // 101 Kumar 78.53
Constructor 2 102 Sumit 89.27
{ Roll = r; 103 Kunal 67.38
strcpy(Name , nm);
Marks = mks; }
Student(char nm[],int r,float mks) //
Constructor 3
{ Roll = r;
strcpy(Name , nm);
Marks = mks; }
void Display()
{ cout<<"\n\t"<<Roll<<"\t"<<Name<<"\t"
<<Marks; } }; BY ZIA AKBAR 143
Dynamic initialization of
objects
• Objects can be initialized dynamically,
initial value of objects are provided
during run time.

• Advantage of it we can provide various


initialization formats by constructor
overloading.

BY ZIA AKBAR 144


#include<iostream.h> Fixed_deposit :: fixed_deposit(long int p, int y1,
Class fixed_deposit int r1)
{ { pamount=p;
long int pamount; y=y1;
int y; r=r1;
float r; rvalue=pamount;
float rvalue; for(int i=1;i<=y1;i++)
Public: rvalue =rvalue*(1+float(r)/100);}
fixed_deposit() { } Void fixed_deposit :: display()
fixed_deposit(long int p,int y1,float {
r1=0.2); cout<<“\n”
fixed_deposit(long int p,int y1, int r1); << “pricipal amount”<<pamount<<“\n”
void display(); <<“return value”<<rvalue<<“\n”;
}; }
Fixed_deposit :: fixed_deposit(long int p,int Int main()
y1, float r1) {
{ pamount =p; fixed_deposit fd1,fd2,fd3;
y-y1; long int p;int y1; float r; int R;
r=r1; Cout<<“enter amount,period,intrest rate in
rvalue=pamount; percent”<<“\n”;
for(int i=1;i<=y1;i++) Cin>>p>>y>>R;
{ rvalue=rvalue*(1.0+r); Fd1=fixed_deposit(p,y,R);
}

BY ZIA AKBAR 145


Cout<<“enter amount,period,intrest rate in
decimal ”<<“\n”;
Cin>>p>>y>>r;
Fd2=fixed_deposit(p,y,r);
Cout<<“enter amount and peroid”<<“\n”;
Cin>>p>>y;
Fd3=fixed_deposit(p,y);
Cout<<“\ndeposit 1”;
Fd1.display();
Cout<<“\n deposit 2”;
Fd2.display();
Cout<<“\n deposit 3”;
Fd3.deposit();
Return 0;
}

BY ZIA AKBAR 146


Destructors
• A destructor is used to destroy the objects
that have been created by constructor.
• It is also a member function of class
whose name same as class name but
preceded by tiled sign(~).
• It never takes any arguments nor return
any value.
• It will be invoked implicitly by the compiler
upon exit from the program to clean up
the storage which is allocated
BY ZIA AKBAR 147
• The new operator is used in constructor to
allocate memory and delete is used to free
in destructors.

• Expl:- ~assign()
• {
– Delete p;
}

BY ZIA AKBAR 148


#include<iostream.h> int main()
Int count =0; {
Class try cout<< “enter main”;
{ public: try t1,t2,t3,t4;
try() {
{ cout<<“block1”;
count++; try t5;
Cout<<“no of objects created”<<count; }
} {
~try() cout<<“block 2”;
{ try t6;
cout<<“no of object destroyed”<<count; }
Count- -; cout<<“again in main”;
}}; Return 0;
}

BY ZIA AKBAR 149


• #include<iostream.h> #include<conio.h>
#include<string.h>

• class Student {

• int Roll; char Name[25]; float Marks;
• • S.Display();
• public: •
• • }
• Student() //Default Constructor { •
Roll = 4; strcpy(Name,"Sumit"); Marks •
= 84.56; } • Output :
• •
• void Display() { cout<<"\n\tRoll : " • Roll : 4 Name : Sumit Marks :
<<Roll; cout<<"\n\tName : "<<Name; 89.56
cout<<"\n\tMarks : "<<Marks; } •
• • End of program.
• ~Student() //Destructor { cout<<"
\n\tEnd of program."; }

• };


• void main() {

• Student S;

BY ZIA AKBAR 150


BY ZIA AKBAR 151
UNIT 3

Inheritance
BY ZIA AKBAR 152
Inheritance
• The mechanism of deriving new class from an old class is
called “INHERITANCE”.

• The old class is known as BASE CLASS

• The NEW class is called DERIVED CLASS / SUB CLASS.

• A class can inherit some or more properties of a base


class.

• A class can inherit properties from more than one classes


and from more than one level.

BY ZIA AKBAR 153


Types of inheritance
1. When a class derived from one class is called
SINGLE INHERITANCE.
2. When a class derived from more than one
base classes then it is known as MULTIPLE
INHERITANCE.
3. When a base class inherited by multiple
classes then it is known as HIERARICAL
INHERITANCE.
4. When a class derived from another derived
class , is called MULTILEVEL INHERITANCE.
5. When a class derived from multiple derived
classes and these derived classes are also
derived from a base class then this
inheritance is known as HYBRID
INHERITANCE.
BY ZIA AKBAR 154
Multiple inheritan
A

A B

Single inheritance C

BY ZIA AKBAR 155


Multi level A

inheritance
A
D
B C

Hierarchical
C inheritance

BY ZIA AKBAR 156


• Hybrid inheritance A

B C

BY ZIA AKBAR 157


Defining derived classes
Class derived class name : visibility –mode base-class-name
{
………..
……….
};
1. Colon indicates that the derived class name is derived from
the base class name.
2. The visibility mode is optional ,if present then it may be
PRIVATE or PUBLIC.
3. The default visibility mode is PRIVATE.
4. Visibility mode specifies whether the features of the base
class are PRIVATELY DERIVED or PUBLICLY DERIVED.
5. A derived class can be defined by specifying its relationship
with the base class in addition to its own details.

BY ZIA AKBAR 158


Class ABC : private XYZ
{
members of ABC
};
• When a base class is privately inherited by
a derived class.
• The public members of the base class
become “private ” of derived class and
these public member of base class can
only be accessed by the member functions
of derived class. They are not accessible to
the objects of the derived class.

BY ZIA AKBAR 159


Class ABC : public XYZ
{
members of ABC
};
When the base class is publicly inherited.
then
• Public members of base class become
“public members” of derived class and
they are accessible to the objects of
derived class.
• In both cases theBYprivate
ZIA AKBAR members of 160
base class are not inherited and will not
• In inheritance, some of the base class
data elements and members functions
are “inherited ”into the derived class.
• We can add our own data and members
functions and thus extend the
functionality of the base class.

BY ZIA AKBAR 161


How to inherit private
member ?
• This can be accomplished by modifying the visibility limit
of the PRIVATE member by making it PUBLIC. but it taking
away the advantage of data abstraction.
• C++ provides another visibility modifier, PROTECTED, that
serve a limited purpose in inheritance.
• A member declared as protected is accessible by the
member functions within its class and any class
immediately derived from it.
• It can not be accessible by the functions outside these
two classes.

BY ZIA AKBAR 162


Example:-
Class example
{
private: visible to member function within its
class
……….
………..
Protected:…….. Visible to member functions of its own
and derived class
…….
Public:

……. Visible to all functions in the program.


……….
};

BY ZIA AKBAR 163


CLASS B NOT INHERITABLE
NOT INHERITABLE
private
protected
public

CLASS D2:PRIVATE B
CLASS D1:PUBLIC B
private private

protected protected

public public

CLASS X : PUBLIC D1:PROTECTED D2

private
protected
public

BY ZIA AKBAR 164


• We can also inherit a class as protected
mode. In this inheritance ,both PUBLIC
and PROTECTED members of the base
class become protected members of
the derived class.
Derived class visibility
Base class Public Private Protected
visibility derivation/ derivation/ derivation /
public Inheritance inhertance
inheritance

Private Not inherited Not inherited Not inherited


Protected Protected Private Protected
Public Public Private protected

BY ZIA AKBAR 165


Important points:-
1. A function that is a friend of the class
can have access to the private and
protected.
2. A member function of a class that is
friend of the class.
3. A member function of a derived class.
4. A friend function and member
functions of class can have direct
access to both PRIVATE and
PROTECTED DATA, WHILE the member
functions of derived class directly 166
BY ZIA AKBAR
Syntax of single
inheritance
• class subclass_name : access_mode
base_class
• {
• //body of subclass
• };

BY ZIA AKBAR 167


// Derived class
• Single inheritance
#include <iostream>
class Rectangle: public Shape {
public:
• using namespace std; int getArea() {
• // Base class return (width * height);
• class Shape { }
• protected:
};
• int width;
• int height;

int main(void) {
public:
• void setWidth(int w) {
Rectangle Rect;
• width = w; Rect.setWidth(5);
• } Rect.setHeight(7);
• void setHeight(int h) { // Print the area of the object.
• height = h; cout << "Total area: " << Rect.
• } getArea() << endl;
• };
return 0;
} AKBAR
BY ZIA 168
How to declare multilevel
inheritance
Synatx:-
class X{
……….
};
Class Y: public X
{
……….
};
Class Z:public Y
{
………….
};
The class Z contain the its own data member and member
function + data members and member functions of its parent
Y as well as its grand parent X’s data members and member
functions. BY ZIA AKBAR 169
• // C++ program to implement • // sub class derived from two
• // Multilevel Inheritance base classes
• #include <iostream> • class Car: public fourWheeler{
• using namespace std; • public:
• • car()
• // base class • {
• class Vehicle • cout<<"Car has 4 Wheels"
• { <<endl;
• • }
public:
• • };
Vehicle()
• •
{
• • // main function
cout << "This is a Vehicle"
<< endl; • int main()
• } • {
• }; • //creating object of sub class
• class fourWheeler: public will
Vehicle • //invoke the constructor of
• { public: base classes
• • Car obj;
fourWheeler()
• • return 0;
{
• • }
cout<<"Objects with 4
wheels are vehicles"<<endl;
• }
• };
BY ZIA AKBAR 170
How to declare multiple
inheritance
Class x{
……..
};
Class Y{
……..
};
Class Z :visibility mode X, visibility mode Y//{visibility mode
either public or private}
{
………
};
The class Z contain all the data members and member
functions of its parents(X,Y).

BY ZIA AKBAR 171


• // multiple inheritance.cpp
• #include •class C : public A, public B //C is
• using namespace std; derived from class A and class B
• class A •{
• { • public:
• public: • void sum()
• int x; • {
• void getx() • cout << "Sum = " << x + y;
• { • }
• cout << "enter value of x: "; cin >> •};
x; •int main()
• } •{
• }; • C obj1; //object of derived class
• class B C
• { • obj1.getx();
• public: • obj1.gety();
• int y; • obj1.sum();
• void gety() • return 0;
• { •} //end of program
• cout << "enter value of y: "; cin >>
y;
• }
• };

BY ZIA AKBAR 172


How to declare hierarchal
inheritance
Class account
{ Class fixed deposit:public account
……… {
}; ……………
};
Class saving account: Class short term:public fixed deposit
public account {
{ ……………..
………… };
Class longterm : public fixed deposit
}; {
Class current account: ……………..
public account }
{
…………………
};

BY ZIA AKBAR 173


// C++ program to implement
// Hierarchical Inheritance
• #include <iostream> • // second sub class
• using namespace std; • class Bus: public Vehicle
• • {
• // base class •
• class Vehicle • };
• { •
• public: • // main function
• Vehicle() • int main()
• { • {
• cout << "This is a Vehicle" << endl; • // creating object of sub class will
• } • // invoke the constructor of base class
• }; • Car obj1;
• • Bus obj2;
• • return 0;
• // first sub class • }
• class Car: public Vehicle
• {

• };

BY ZIA AKBAR 174


How to declare hybrid
inheritance
Class student
{
………
};
Class test:public student
{
………
};
Class sports
{
…………..
};
Class result:public test ,public sports
{
…………..
};
BY ZIA AKBAR 175
// C++ program for Hybrid
• #include <iostream>Inheritance
• // first sub class
• using namespace std; • class Car: public Vehicle
• • {
• // base class •
• class Vehicle • };
• { •
• public: • // second sub class
• Vehicle() • class Bus: public Vehicle, public
• { Fare
• cout << "This is a Vehicle" << endl; • {
• } •
• }; • };
• •
• //base class • // main function
• class Fare • int main()
• { • {
• public: • // creating object of sub class
• Fare() will
• • // invoke the constructor of base
{ class
• cout<<"Fare of Vehicle\n"; • Bus obj2;
• } • return 0;
• }; • }
BY ZIA AKBAR 176
Virtual base class
• When a child is inherited from two classes and
these classes are also derived from a base class
then a problem arises that is ambiguity means
child would have duplicate sets of the members
inherited from grand parent.

• This problem can be removed by making a


common base class a VIRTUAL BASE CLASS .

BY ZIA AKBAR 177


• Example:-
Class A
{
……….
};
Class B:public virtual A
{
…………..
};
Class c:virtual public A
{
……………….
};
Class D:public B,public C
{
…………….
};

BY ZIA AKBAR 178


Constructors in derived classes

• If any base class contains a constructor with one or more


arguments ,the it is necessary for the derived class to have
a constructor and pass the arguments to the base class.
• The base class constructor executed first then derived
class constructor executed.
• The constructor of the derived class receives the entire
list of arguments and passes them to base constructor in
order to in which they are declared class.
• In case of multiple inheritance ,the base classes are
constructed in order in which they appear in the
declaration of the derived class.

BY ZIA AKBAR 179


BY ZIA AKBAR 180
Aggregation,
composition and
classification

BY ZIA AKBAR 181


Relations between
CLASSES
• The relationship between the classes explains
how the classes are connected to each other’s
and how they will behave.
• Mainly there are four type of relationship is
present :
 Inheritance
 Association
 Aggregation
 Composition

BY ZIA AKBAR 182


• Inheritance:
• One class can use features from another class to extend
its functionality.
• Inheritance based on IS-A Relationship.
• Inheritance is uni-directional. Inheritance is indicated by
a solid line with a arrowhead pointing at the super class.

BY ZIA AKBAR 183


Association
• Association represents a relationship between
two or more objects where all objects have their
own life cycle and there is no owner.
• Association is based on HAS-A Relationship.
• Association can be one-to-one, one-to-many,
many-to-one, many-to-many.
• Composition and Aggregation are the two forms
of association.

BY ZIA AKBAR 184


• In above example two separate classes
Bank and Employee are associated
through their Objects. Bank can have
many employees, So it is a one-to-many
relationship.
BY ZIA AKBAR 185
BY ZIA AKBAR 186
Aggregation

• Aggregation is a special form of Association where all objects have


their own life cycle but there is ownership.
• This represents a-part-of relationship based on HAS-A Relationship.
• This is represented by a hollow diamond followed by a line.
• In Aggregation, both the entries can survive individually which
means ending one entity will not effect the other entity

We can take an example of relationship between Department and Teacher. A


Teacher may belongs to many departments. Hence Teacher is a part of many
departments. But if we delete a Department, Teacher Object will not destroy.

BY ZIA AKBAR 187


Composition
• Composition is a restricted form of Aggregation in which two
entities are highly dependent on each other.
• It represents part-of-death relationship, in this both the entities are
dependent on each other.
• When there is a composition between two entities, the composed
object cannot exist without the other entity.
• This is represented by a solid diamond followed by a line.

• Here we can take another example of relationship between Building


and Room. A Building can have many Rooms but a Room cannot
belong to many Buildings. If we destroy Building, Room will be
automatically destroyed.

BY ZIA AKBAR 188


polymorphism

BY ZIA AKBAR 189


Polymorphi
sm
The word polymorphism is derived from Greek
word Poly
which means many and morphos which means
forms.
Polymorphism can be defined as the ability to use
the same name for two or more related but
technically different tasks.
Eg-woman plays role of daughter,sister,wife,
mother etc.

1 BY ZIA AKBAR 190


9
polymorphism
• The word polymorphism comes from Greek and means
having several different forms.

• This is one of the essential concepts of object-oriented


programming. Where inheritance is related to classes
and (their hierarchy), polymorphism is related to object
methods.

• In general there are three types of polymorphism:


• Overloading polymorphism
• Inclusion polymorphism (also called redefinition or
overriding) by using virtual function
• Parametric polymorphism (also called template
polymorphism or generic programming)
BY ZIA AKBAR 191
Overloading in
C++
What is overloading
–Overloading means assigning multiple
meanings to a function name or operator symbol
–It allows multiple definitions of a function with
the same name, but different signatures.
C++ supports
–Function overloading
–Operator overloading

1 BY ZIA AKBAR 192


9
Why is Overloading
Useful?
Function overloading allows
functions that conceptually perform
the same task on objects of
different types to be given the
same name.

Operator overloading provides a


convenient notation for
manipulating user-defined objects
with conventional operators.
1 BY ZIA AKBAR 193
9
FUNCTION
OVERLOADIN
G

1 BY ZIA AKBAR 194


9
Function
Overloading
Is the process of using the same name for two
or more functions
Requires each redefinition of a function to use
a different function signature that is:
different types of parameters,
or sequence of parameters,
or number of parameters
Is used so that a programmer does not have to
1 remember multiple function names
BY ZIA AKBAR 195
9
Function
Overloading
Two or more functions can have the same name
but different parameters
Example:
int max(int a, int b) float max(float a, float b)
{ {
if (a>= b) if (a>= b)
return a; else return a; else
return b; return b;
} }

1 BY ZIA AKBAR 196


9
Overloading Function Call
Resolution
Overloaded function call resolution is done
by compiler during compilation
– The function signature determines which
definition is used
a Function signature consists of:
– Parameter types and number of
parameters supplied to a function
a Function return type is not part of function
signature and is not used in function call
resolution

1 BY ZIA AKBAR 197


9
void sum(int,int);
void sum(double,
double); void sum(char,
char); void main()
{
int a=10,b=20 ; double
c=7.52,d=8.14; char
e=‘a’ , f=‘b’ ;
sum(a,b);
//calls sum(int x,int y)
sum(c,d);
//calls sum (double x,double
y)
sum(e,f); // calls sum(char x,char
} y)
void sum(int x,int y)
{
vout<<“\n sum of integers are”<<x+y;
}
void sum(double x,double y)
{
cout<<“\n sum of two floating no are”
<<x+y;
}
void sum(char x,char y)
{
8 BY ZIA AKBAR 198
cout<<“\n sum of characters are”
<<x+y;
Output:
Sum of integers 30
sum of two floating no are
15.66 sum of characters
are 195

19 BY ZIA AKBAR
9
Void area(int) Void area(int,int);
Void area(int,int,int); Int main()
{
Int side=10,le=5,br=6,a=4,b=5,
c=6; Area(side);
Area(le,br);
Area(a,b,c); Getch(); Return 0;
}
Void area(int x)
{ cout<<“area is”<<x*x;
}
Void area(int x,int y)
{cout<<“area of rectang;e”
=<<x*y;
}
Void area(int x,int y,int z)
{cout<<“volume is”<<x*y*z;
}

20 BY ZIA AKBAR
0
Involves
following
Steps.
Compiler first tries to find the Exact match in
which the type of argument are the same,and
uses that func.
If an exact match is not found,the compiler user
the integral promotions to the actual argument
such as,char to int, float to double.
When either of them fails ,build in conversions are
used(implicit conversion) to the actual arguments
and then uses the function whose match is
unique.but if there are multiple matches,then
compiler will generate an error message.
20 BY ZIA AKBAR
1
long
For ex: square(long n)

• long square(double x)
• Now a func. call such as square(10) will
cause an error because int argument can
be converted into long also and double
also.so it will show ambiguity.

• User defined conversion are followed if


all the conversion are failed.
20 BY ZIA AKBAR
2
Overloading polymorphism

• Overloading polymorphism is where functions of the same


name exist, with similar functionality, in classes which are
completely independent of each other .

• Overloading polymorphism therefore allows us to define


operators whose behavior will vary depending on the
parameters that are applied to them.

• for example, to add the + operator and make it behave
differently according to whether it refers to an operation
between two integers (addition) or between two character
strings (concatenation).

BY ZIA AKBAR 203


Operator overloading
• Mechanism provide the operators with
special meanings to an operator is known as
“operator overloading”.

• C++ permits us to add two variables of user-


defined types with the same syntax that is
applied to the basic types.

• Operator overloading provides a flexible


option for the creation of new definitions for
most of the c++ operators.

BY ZIA AKBAR 204


• When an operator is overloaded ,its
original meaning is not lost.

• The semantics of an operator can be


extended , we cannot change its syntax
means grammatical rules that govern its
use such as the number of operands,
precedence and associativity.

BY ZIA AKBAR 205


Defining operator overloading
• We can define operator overloading by a
specific function, called operator function,
which describes the task.
• Syntax:-
• Return type classname :: operator OP(arguments)
{
function body;
}
• Return type is the type of value returned by operation
• Op is the operator being overloaded.
• Operator is the function name.

BY ZIA AKBAR 206


characteristics
1. Operator function must be either member
function or friend function.

2. When operator function is member function of


class then no arguments for unary operators and
only one argument for binary operators
overloading.

3. When operator function is friend function then


one argument for unary operator and two
arguments for binary operator overloading.

4. Arguments are passedBY by value or by reference.


ZIA AKBAR 207
Process for overloading
1. Create a class that define the data type that
is to be used by the overloading operation.

2. Declare the operator function in the public


section of the class.

3. It may be either member function or friend


function of class.

4. Define the operator function to implement


the required operations.
BY ZIA AKBAR 208
• Overloaded operator functions can be
invoked by following expression
• For unary operator:-
– Op X or X op
– This calling interpreted as
• Operator op(X){when operator function is friend function}
• operator op (){when operator function is member function}

• For binary operator:-


– X op Y
– This calling interpreted as
• X.operator op (y){when operator function is member function}
• Operator op(X,Y){when operator function is friend function}

BY ZIA AKBAR 209


Operator that can not be
overload
1. Class member access operators{.,.*}

2. Scope resolution operator {::}

3. Size of operator {size of }

4. Conditional; operator{? :}
BY ZIA AKBAR 210
Unary operator overloading
#include<iostream.h> Void unary:: operator –( )
Class unary {
{
int x,y,z; x=-x;
public: y=-y;
void getdata(int a,int b,int c); z=-z;
void display(); }
void operator –();
}; int main()
Void unary:: getdata(int a, int b,int c) {
{ unary u;
x=a; u.getdata(10,-20,30) ;
y=b;
z=c; cout<<“u=“;
} u.display();
Void display() -u;
{ cout<<“u=“;
cout<<x<<“”;
cout<<y<<“ “; u.display( );
cout<<z<< “ “; return 0;
} }

BY ZIA AKBAR 211


Binary operator overloading
Void complex:: display()
• #include< iostream.h> {
• Class complex cout<<x<<“+j”<<y<<“\n”;
}
• {
Float x,y;
Public: Int main()
complex() { } {
complex(float real,float imag) complex c1,c2,c3;
{x=real ;y= imag;} C1=comlex(2.5,3.5);
Complex operator +( complex); C2=complex(1.6,2.7);
Void display(); C3=c1+c2;
}; Cout<<“c1=”;
Complex complex :: operator
+(complex c) C1.display();
{ Cout<<“c2=”;
complex temp; C2.display();
Temp.x=x+c.x; Cout<<“c3 =”;
Temp.y=y+c.y; C3.display();
Return (temp); Return 0;
}
}
BY ZIA AKBAR 212
Overloading Increment ++ &
Decrement ----
#include <iostream>
using namespace std;
class Time {
private:
int hours; // 0 to 23
int minutes; // 0 to 59
public:
// required constructors
Time() {
hours = 0;
minutes = 0;
}
Time(int h, int m) {
hours = h;
minutes = m;
}
// method to display time
void displayTime() {
cout << "H: " << hours << " M:" << minutes <<endl;
}
BY ZIA AKBAR 213
Cotnd..
// overloaded postfix ++ int main()
operator
Time operator++( int ) { { Time T1(11, 59), T2(10,40);
// save the original value ++T1; // increment T1
Time T(hours, minutes); T1.displayTime(); // display
// increment this object
++minutes; T1
if(minutes >= 60) { ++T1; // increment T1 again
++hours; T1.displayTime(); // display
minutes -= 60; T1
}
// return old original value T2++; // increment T2
return T; T2.displayTime(); // display
} T2
};
T2++; // increment T2 again
T2.displayTime(); // display
BY ZIA AKBAR 214
T2
Rules for overloading
1. Only existing operator can be overloaded. new operators can
not be created.
2. The overloaded operator must have at least one operand of
user defined data type.
3. We can not change the basic meaning of operator.
4. Overloaded operator apply the original rule of operator.
5. We can not use friend function functions to overload certain
operator..like
• = assignment operator.
• ( ) function call
• -> class member access operator.
• [ ] subscripting operator.

BY ZIA AKBAR 215


Virtual function
• As its name show that something exits by its effects but
not in reality.

• The concept of virtual function is simple as a member


function but it does not really exist while appears only
where it needed.

• Virtual function is a method to implement the concept of


polymorphism. It implements dynamic binding.

• Virtual function is a member of base class and it


overridden in derived classes.

BY ZIA AKBAR 216


• Use virtual keyword when defining a virtual
function in base class.
• The keyword virtual is implicit in member
functions overridden in derived classes.
• The constant member function which is
virtual, the keyword const is part of its
signature and also ensure the const
keyword is in signature of overridden
function in derived classes.
• A virtual function of class can be a friend of
another class.
• the virtual function mechanism works only
in public derivation not in protected and
private.
• A virtual function can not be a global or
BY ZIA AKBAR 217
static because it is dynamic in nature.
• When a base class contain more than one
virtual functions the that class is known as
“abstract class”.
• The basic need of virtual function is to
implement a different functionality in derived
class.

• Synatx:-
Class class_name{
{
Virtual return type function_name(signature)
{
…….
…….
}
}; BY ZIA AKBAR 218
• We should use pointer object of base class
for accessing the virtual function , we can’t
use the object name and dot operator.

• We can access virtual function by using


object name and dot operator but the
runtime polymorphism is achieve when we
using object pointer.

• The virtual function must be member of


some class.

• A virtual function in base class must be


define, even though it may not be used.
BY ZIA AKBAR 219
• The prototypes of virtual function in
base class and derived classes must
be same, if it will differ then virtual
function mechanism ignored.

• We can not have virtual constructors,


but we have virtual destructors.

BY ZIA AKBAR 220


# include<iostream.h>
#include<conio.h>
Class base_class
{
public:
virtual void show()
{ Void main()
cout<<”hello ! This is base class virtual {
show function execution”; clrscr();
base_class *b1,*b2;
}
b1=new base_class();
}; B1->show();
Class derived: public base_class B2=new derived();
{ B2->show();
public: Getch();
}
void show()
{
cout<<”hi! Now you are in derived class
show function execution”;
}
};

BY ZIA AKBAR 221


#include<iostream.h> Int main()
#include<conio.h>
{
Class first
{ public: first f;
void display() second s;
{ cout<<“display function of first *f1;
first class”;} f1=&f;
virtual void show()
f1->display();
{ cout<<“show function of first
class”; } f1->show();
}; f1=&s;
Class second: public first f1->display();
{ public: f1->show();
void display() {
cout<<“display function of
return 0;
second class”;} }
void show() { cout<<“show
function of second class”;}
}
BY ZIA AKBAR 222
Abstract Class
• Abstract Class is a class which contains at least one Pure Virtual
function in it.
• Abstract classes are used to provide an Interface for its sub classes.
• Classes inheriting an Abstract Class must provide definition to the
pure virtual function, otherwise they will also become abstract class.

BY ZIA AKBAR 223


Characteristics of Abstract Class

• Abstract class cannot be instantiated, but pointers and


references of Abstract class type can be created.
• Abstract class can have normal functions and variables
along with a pure virtual function.
• Classes inheriting an Abstract Class must implement all
pure virtual functions, or else they will become Abstract
too.

BY ZIA AKBAR 224


Pure Virtual Functions in C++

• Pure virtual Functions are virtual functions with no definition.


• They start with virtual keyword and ends with = 0.
• Here is the syntax for a pure virtual function,
• virtual void functionName() = 0;

BY ZIA AKBAR 225


class number
{ public:
virtual void add() = 0;
};

• Here, the pure virtual function is:


virtual void add() = 0
• the class number is an abstract class.

BY ZIA AKBAR 226


//Abstract base class
class Base
{ public:
virtual void show() = 0; // Pure VirtualFunction
};
class Derived:public Base
{ public:
void show()
{ cout << "Implementation of Virtual Function in Derived
class\n";
}
};
Int main()
{
Derived d;
d.show();
}

BY ZIA AKBAR 227


Parametric polymorphism
• Parametric polymorphism is the ability to define several
functions using the same name, but using different
parameters (name and/or type). Parametric polymorphism
automatically selects the correct method to be adopted
according to the type of data passed in the parameter.

• Parametric Polymorphism is a way to define types or


functions that are generic over other types.

• Generic means type independent.

• If the code is written without mention of any specific type and


thus can be used transparently with any number of new types,
it is called parametric polymorphism. In the object-oriented
programming community, this is often called generic
programming.
BY ZIA AKBAR 228
• To implement the concept of generic
programming in oop we uses the
concept of “template”.

BY ZIA AKBAR 229


BY ZIA AKBAR 230
UNIT 4

Template

BY ZIA AKBAR 231


Templates

It is a new concept develop and added in c++ to


support generic programming .

Generic programming is an approach where


generic types are used as parameters due to this
they work for a variety of suitable data types.

Templates are a feature of the C++ programming


language that allow functions and classes to
operate with generic types. This allows a function
or class to work on many different data types
without being rewrittenBYfor each one.
ZIA AKBAR 232
• A template can be treat like a macro.
• A template is defined with a parameter
that would be replaced by specified data
types at time of actual use of the function
/class, so sometimes templates are called
parameterized classes or functions.
• A family of classes or function can be
created through templates.
– Like :- a class template for an array class
permit to create arrays of various data types
such that …INT ARRAY, FLOAT ARRAY.
BY ZIA AKBAR 233
• Template is classified into two parts
1. function template
2. class template

• Function template
– Function templates are special functions that
can operate with generic types. This allows us
to create a function template whose
functionality can be adapted to more than one
type or class without repeating the entire code
for each type.
BY ZIA AKBAR 234
• In C++ this can be achieved using template
parameters. A template parameter is a special kind
of parameter that can be used to pass a type as
argument: just like regular function parameters can
be used to pass values to a function.

• template parameters allow to pass also types to a


function. These function templates can use these
parameters as if they were any other regular type.

BY ZIA AKBAR 235


The format for declaring function templates with type
parameters is:
template <class identifier> function_declaration;
template <typename identifier> function_declaration.

The only difference between both prototypes is the


use of either the keyword class or the keyword
typename. Its use is indistinct, since both expressions
have exactly the same meaning and behave exactly
the same way.

To use this function template we use the following


format for the function call:

function_name (parameters);
BY ZIA AKBAR 236
function template
#include <iostream>
template <class T>
T GetMax (T a, T b)
{

T result;
result = (a>b)? a : b;
return (result);
}
int main ()
{
Int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax(i,j);
n=GetMax(l,m);
cout << k << endl;
cout << n << endl;
return 0;
}

BY ZIA AKBAR 237


The template function includes only one template parameter
(class T) and the function template itself accepts two parameters,
both of this T type, we cannot call our function template with two
objects of different types as arguments:

int i;
long l;
k = GetMax (i,l);
This would not be correct, since our GetMax function template
expects two arguments of the same type, and in this call to it we
use objects of two different types.

We can also define function templates that accept more than one
type parameter, simply by specifying more template parameters
between the angle brackets. this is known as template function
with multiple parameter. For example:

template <class T, class U>


T GetMin (T a, U b)
{
return (a<b?a:b);
BY ZIA AKBAR 238
}
In this case, our function template GetMin()
accepts two parameters of different types and
returns an object of the same type as the first
parameter (T) that is passed. For example,
after that declaration we could call GetMin()
with:

int i,j;
long l;
i = GetMin<int,long> (j,l);

BY ZIA AKBAR 239


Overloading of template
functions
• A template function may be overload by any of
two ways
1. By template functions
2. Ordinary functions of its name
– We follow following points in overloading
– Call an ordinary function that has an exact match.
– Call a template function that could be create with an
exact match.
– Try only normal overloading and call the best matches
function

BY ZIA AKBAR 240


Class templates
• We also have the possibility to write class templates, so that a
class can have members that use template parameters as types.

• For example:
template <class T>
class mypair
{
T values [2];
public:
mypair (T first, T second)
{
values[0]=first;
values[1]=second;
}
};

BY ZIA AKBAR 241


• The class that we have just defined serves
to store two elements of any valid type.
• For example,
– if we wanted to declare an object of this class
to store two integer values of type int with the
values 115 and 36, we would write:
– mypair<int> myobject (115, 36);

– this same class would also be used to create an


object to store any other type:

mypair<double> myfloats (3.0, 2.18);


BY ZIA AKBAR 242
• the only member function in the previous class
template has been defined inline within the class
declaration itself. In case that we define a
function member outside the declaration of the
class template, we must always precede that
definition with the template <...> prefix:

BY ZIA AKBAR 243


class templates

#include <iostream>
template <class T>
class mypair
{
T a, b;
public:
mypair (T first, T second)
{
a=first;
b=second;
}
T getmax ();
};
template <class T>
T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
int main ()
{
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}

BY ZIA AKBAR 244


EXCEPTION HANDLING

BY ZIA AKBAR 245


EXCEPTIONS
Exceptions are run time anomalies or unusual
conditions that a program may encounter during
execution.
Conditions such as
Division by zero
Access to an array outside of its bounds
Running out of memory
Running out of disk space
It was not a part of original C++.
It is a new feature added to ANSI C++.

BY ZIA AKBAR 246


EXCEPTION HANDLING
Exceptions are of 2 kinds
Synchronous Exception:
Out of range
Over flow
Asynchronous Exception: Error that are caused by
causes beyond the control of the program
Keyboard interrupts
In C++ only synchronous exception can be
handled.

BY ZIA AKBAR 247


EXCEPTION HANDLING (CONT…)
Exception handling mechanism

Find the problem (Hit the exception)

Inform that an error has occurred (Throw the exception)


Receive the error information (Catch the exception)
Take corrective action (handle the exception)

BY ZIA AKBAR 248


EXCEPTION HANDLING MECHANISM
It is basically build
try block
upon three keywords
Try Detects and
throws an
Throw exception
Catch

Exception object
catch block

Catch and handle


the exception

BY ZIA AKBAR 249


EXCEPTION HANDLING MECHANISM (CONT…)
The keyword try is used to preface a block of
statements which may generate exceptions.

When an exception is detected, it is thrown using a


throw statement in the try block.

A catch block defined by the keyword ‘catch’


catches the exception and handles it appropriately.

The catch block that catches an exception must


immediately follow the try block that throws the
exception.

BY ZIA AKBAR 250


EXCEPTION HANDLING MECHANISM (CONT…)
try
{
… // Block of statements
throw exception; // which detect and
… // throws an exception
}
catch(type arg) // catch exception
{
… // Block of statement
… // that handles the
… // exception
}

BY ZIA AKBAR 251


EXCEPTION HANDLING MECHANISM (CONT…)
Exceptions are objects used to transmit information
about a problem.

If the type of the object thrown matches the arg


type in the catch statement, the catch block is
executed.

If they do not match, the program is aborted using


the abort() function (default).

BY ZIA AKBAR 252


#include<iostream.h>
catch(int i)
#include<conio.h>
{
void main()
cout<<"Answer is infinite because a-
{
b is:"<<i;
int a,b,c;
}
float d;
clrscr();
getch();
cout<<"Enter the value of a:";
}
cin>>a;
cout<<"Enter the value of b:";
cin>>b;
cout<<"Enter the value of c:";
cin>>c;

try
{
if((a-b)!=0)
{
d=c/(a-b);
cout<<"Result is:"<<d;
}
else
{
BY ZIA AKBAR 253
throw(a-b);
EXCEPTION HANDLING MECHANISM (CONT…)
Often, Exceptions are thrown by functions that are
invoked from within the try blocks.

The point at which the throw is executed is called


the throw point.

Once an exception is thrown to the catch block,


control cannot return to the throw point.

BY ZIA AKBAR 254


#include<iostream.h>
Void divide(int x, int y, int z)
{
Cout<<“we are in the function”<<endl;
If ((x-y)!=0)
{
Int a =z/(x-y);
Cout<< value is <<a<<endl;
}
Else
{
Throw(x-y);
}
}
Int main()
{
try
{
cout<<“inside try block”;
divide(20,20,30);
divide(20,30,40);
}
catch(int i)
{
cout<<“caught the exception”<<endl;
}
return 0;
}

BY ZIA AKBAR 255


EXCEPTION HANDLING MECHANISM (CONT…)

Invoke function

throw point try block catch block


Invokes a
Function that
function that Catch and handle
causes an
contains an the exception
exception
exception

Throw exception

BY ZIA AKBAR 256


THROWING MECHANISM
The throw statement can have one of the following
3 forms
throw(exception)
throw exception
throw //used to re-throw a exception

The operand object exception can be of any type,


including constant.

It is also possible to throw an object not intended


for error handling.

BY ZIA AKBAR 257


THROWING MECHANISM (CONT…)
Throw point can be in a deeply nested scope within
a try block or in a deeply nested function call.

In any case, control is transferred to the catch


statement.

BY ZIA AKBAR 258


CATCHING MECHANISM
The type indicates the catch(type arg)
type of exception the {
catch block handles.

the parameter arg is an …
optional parameter …
name. }
The catch statement
catches an exception
whose type matches
with the type of the
catch argument.

BY ZIA AKBAR 259


CATCHING MECHANISM (CONT…)
If the parameter in the catch statement is named,
then the parameter can be used in the exception
handling code.

If a catch statement does not match the exception it


is skipped.

More than one catch statement can be associated


with a try block.

BY ZIA AKBAR 260


CATCHING MECHANISM (CONT…)
try
{
throw exception;
}
catch(type1 arg)
{
// catch block 1
}
catch(type2 arg)
{
// catch block 2
}


catch(typeN arg)
{
// catch block N
}

BY ZIA AKBAR 261


CATCHING MECHANISM (CONT…)
When an exception is thrown, the exception
handlers are searched in order for a match.

The first handler that yields a match is executed.

If several catch statement matches the type of an


exception the first handler that matches the
exception type is executed.

BY ZIA AKBAR 262


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

BY ZIA AKBAR 263


CATCHING MECHANISM (CONT…)
Catch all exception

catch (…)
{
// statement for processing
// all exception
}

BY ZIA AKBAR 264


#include<iostream.h>
Void check(int a)
{
try
{
If(a==0) throw x;
If(a==-1) throw ‘x’;
If(a==2.3) throw 2.3;
}
Catch(…)
{
cout<<“caught exceptions”;
}
}
Int main()
{
Cout<<“” testing of generic catch”;
Check(-1);
Check(0);
Check(2.3);
Return 0;
}

BY ZIA AKBAR 265


RETHROWING AN EXCEPTION
A handler may decide to rethrow the exception
caught without processing it.

In such a case we have to invoke throw without


any arguments as shown below
throw;

This causes the current exception to be thrown to


the next enclosing try/catch sequence and is caught
by a catch statement listed after the enclosing try
block

BY ZIA AKBAR 266


#include<iostream.h> Int main()
Void divide(double x,double y) {
{ cout<<“inside main function”<<endl;
cout<<“inside divide function”<<endl; try
try { divide(10.4,3.4);
{ divide(20.4,4.5);
if (y==0.0) }
throw y catch(double)
else {
cout<< “division ”<<x/y<<endl; cout<<“caught double inside main
} function”<<endl;
catch (double) }
{ Cout<<“end of main function”<<endl;
cout<<“caught double inside function” }
<<endl;
throw;
}
cout<<“end of function”<<endl;
}

BY ZIA AKBAR 267


SPECIFYING EXCEPTION
It is possible to restrict a function to throw certain
specific exceptions by adding a throw list clause to
the function definition.

type function(arg-list) throw(type-list)


{
………
………
………
}

BY ZIA AKBAR 268


SPECIFYING EXCEPTION (CONT…)
The type-list specifies the type of exception that
may be thrown.

Throwing any other kind of exception will cause


abnormal program termination.

If you want to prevent a function from throwing any


exception, you may do so by making the type-list
empty.

BY ZIA AKBAR 269


#include<iostream.h>
Void check(int a) throw(int,double) Catch (char c)
{ {
cout<<“caught a character”<<endl;
If(a==0) throw ‘x’; }
else Catch(int m)
If(a==1) throw x; {
else cout<<“caught a integer”<<endl;
If(a==-1) throw 1.0; }
cout<<“end of function block”; Catch(double d)
} {
Int main() cout<<“caught a double”<<endl;
{ }
Try Cout<<“end of try and catch ”<<endl;
{ Return 0
Cout<<“” testing of throw restrictions”<< }
endl<< “a==0”<<endl;
Check(0);
Cout<<“a==1”<<endl;
Check(1);
Cout<<“a==-1”<<endl;
Check(-1);
Cout<<“a==2”<<endl; BY ZIA AKBAR 270
Check(2);
BY ZIA AKBAR 271
Namespaces
• When a header file, such as iostream, is
included in a program
– Global identifiers in the header file also
become global identifiers in the program
• If a global identifier in a program has
the same name as one of the global
identifiers in the header file
– The compiler will generate a syntax error
(such as identifier redefined)
• The same problem can occur if a
program uses third party libraries
BY ZIA AKBAR 272
Namespaces (continued)
• To overcome this problem, third party
vendors begin their global identifiers
with a special symbol
• Because compiler vendors begin their
global identifier with _ (underscore)
– To avoid linking errors, do not begin
identifiers in your program with _
• ANSI/ISO standard C++ attempts to
solve this problem of overlapping
global identifier names with
BY ZIA AKBAR
the 273
namespace mechanism
• Namespaces allow to group entities
like classes, objects and functions
under a name. This way the global
scope can be divided in "sub-scopes",
each one with its own name.

• The functionality of namespaces is


especially useful in the case that there
is a possibility thatBYaZIAglobal
AKBAR
object or 274
function uses the same identifier as
Syntax: namespace
The format of namespaces is:

namespace identifier
{
entities
}

Where identifier is any valid identifier and entities is the set of classes,
objects and functions that are included within the namespace. For
example:

namespace myNamespace
{
int a, b;
}

In this case, the variables a and b are normal variables declared within a
namespace called myNamespace. BY ZIA AKBAR 275
BY ZIA AKBAR 276
Accessing a namespace
Member
• The scope of a namespace member is
local to the namespace
• Usually two ways a namespace
member can be accessed outside the
namespace
• One way is to use the syntax:
namespace_name::identifier
• To access the member rate of the
namespace globalType, the following
BY ZIA AKBAR 277
statement is required:
Accessing a namespace
Member (continued)
• To access the function printResult, the
following statement is required:
globalType::printResult();
– Alternatively, the using declaration allows the names
of the elements to be used directly

• To simplify the accessing of all namespace


members:
using namespace namespace_name;
• To simplify the accessing of a specific
namespace member:
using namespace_name::identifier;
BY ZIA AKBAR 278
Important points
• There is no semicolon directly after the closing brace of the
namespace declaration.

• The elements declared within the braces of namespace do not


clash with another name space elements and global names
because each namespace has its unique scope.

• The name of the namespace and the scope resolution operator:


: are used to resolve access to given namespace’s members
explicitly.

• It is possible to use an alias for a namespace and is useful


when referring to long namespace name.

BY ZIA AKBAR 279


The using Statement
• After the using statement
– Not necessary to precede the
namespace_name and the scope
resolution operator before the namespace
member
• If a namespace member and a global
identifier or a block identifier have the
same name
– namespace_name and scope resolution
operator must precede the namespace
BY ZIA AKBAR 280
member
• Items declared in the C++ Standard
Library are declared in the std
namespace
• C++ include files for several functions
are in the std namespace
– To include input and output functions from
the C++ library, write
include <iostream>
using namespace std;
BY ZIA AKBAR 281
#include <iostream>
using namespace std;

namespace first
{
int var = 5;
}

namespace second
{
double var = 3.1416;
}

int main () {
cout << first::var << endl;
cout << second::var << endl;
return 0;
}
BY ZIA AKBAR 282
Defining class inside the
namespace
Namespace MYNAME The defining object of the
{ class best.
Class best Syntax:-
{ Namespace name:: class
String name; name object name;
Public:
Ex:
Best( cost char* temp)
{ MYNAME ::best obj(“hello”)
Name= temp;

}
};
}
BY ZIA AKBAR 283
Declaring inside and
defining of function
outside
Namespace myspace
namespace:
{ function declaration inside namespace
Int num;
Void input();
}
Void myspace::input()
{
code; function definition outside namespace
}
Myspace::input(); function call
When we using the USING method then function call should be
as follows:
Using namespace myspace;
Input();

BY ZIA AKBAR 284


Namespace aliases
• To reduce the difficulties of long name
with namespace by using the concept
of aliases.
• The syntax is as follows:

Namespace
alias_name=namespace_name;

Namespace newname= existing name;


BY ZIA AKBAR 285
Nesting of namespace
• We can a declare a namespace with in
another namespace that is called
nesting of it.
Namespae S
{
Namespase S1
{
Int m=100;
}
……. BY ZIA AKBAR 286
}
#include <iostream>
using namespace std;

// first name space


namespace first_space{
void func(){
cout << "Inside first_space" << endl;
}
// second name space
namespace second_space{
void func(){
cout << "Inside second_space" << endl;
}
}
}
using namespace first_space::second_space;
int main ()
{

// This calls function from second name space.


func();

return 0;
}

BY ZIA AKBAR 287


Unnamed namespaces
• A unnamed namespace is one that
does not have a name.
• The member of unnamed namespace
have global scope and accessible in all
scope following the declarartion in the
file.
• We can access them with using any
qualification.
BY ZIA AKBAR 288
#include<iosteam.h>
Using namespace std;
Namespace name1
{
double x=2.34;
Int m=100;
Namespace name2
{
double y=1.23;
}
}
Namespace unnamed namespace
{
int m=200;
}
Int main()
{
cout<<“x=”<<name1::x<<“\n”;
cout<<“m=”<<name1::m<<“\n”;
cout<<“y=”<<name::name2::y<<“\n”;
cout<<“m=”<<m<<“\n”;
Return 0;
}

BY ZIA AKBAR 289


BY ZIA AKBAR 290
Stream and file

BY ZIA AKBAR 291


• The term stream show the flow of data form input
device to system and from disk to display devices.

• C++ provides the ifstream,ofstream,and fstream


classes for processing and manipulating files.
These classes are defined in the <fstream> header
file.

• The ifstream class is for reading data from the file.


• The ofstream class is for witing data to a file.
• The fstream class can be used for both reading
and writing data in a file.
BY ZIA AKBAR 292
• If the data flows FROM TEXT FILE to program
then it is called input stream.
• If it flows out from your program TO TEXT FILE
then it is called output stream.
• C++ uses objects to read/write a stream of
data.
• An input object is called an input stream (LIKE:
cin)and an output object is called an output
stream(LIKE :cout).

BY ZIA AKBAR 293


WE FERFORM FOLLOWING
OPERAION IN THE FILE
• Open the file
• Access the file
• Close the file

BY ZIA AKBAR 294


File (input and output)
• The file is a collection of bits and bytes
that show our collection of information
and stored in storage device.

• A program can read data from file like


reading from keyboard and write output
to a disk file same way as output on
screen.
BY ZIA AKBAR 295
Using file

• For accessing files to perform input


and output function a programmer have
to perform several steps
1. Include header file “fstream”
2. Declare the file streams that will use in
program.
3. Prepare each file for reading/writing by
using a function named open.
4. Specify the name of the file stream in
each input/outputBYstatement.
ZIA AKBAR 296
Opening a file
• A file can be opened in two ways:
1. Using the constructor functions of the class.
2. Using the member function OPEN() of the
class.

• The first method is useful when we use


only one file in the stream. The second
method is used when we want to manage
multiple files using BYone stream.
ZIA AKBAR 297
Opening file using
constructor
• Create a file stream object to manage
the stream using the appropriate class
mean OFSTREAM is used to create
output stream and IFSTREAM to create
the input stream.
• Initialize the file object with the desired
filename.
• Like
– ofstream out(“text.txt”)
BY ZIA AKBAR 298

– Ifstream in(“data”)
EXAMPLE
#include<iostream.h>
#include<fstream.h>
Int main
{Char name[30];
Ofstream outf(“file.txt”);
Cout<<“Enter employee name”;
Cin>> name;
Outf<<name;
Outf.close();
Ifstream inf(“file.txt”);
Inf>>name
Inf.close();
Return 0;
}
OUTPUT: OPEN A FILE “FILE.TXT” THEN DISPLAY YOUR NAME
INTO THAT FILE AND READ YOUR NAME FROM FILE”FILE .TXT”.

BY ZIA AKBAR 299


Opening files using open()
The function open() can be used to open
multiple files that use the same stream
object.
In such cases, we may create a single
stream object and use it to open each
file in turn. Like:SYNTAX
File-stream-class stream-object;
Stream-object.open(“filename”);
BY ZIA AKBAR 300
#include<iostream.h>
#include<fstream.h> Const int N=30;
Int main() Char line[N];
{ Ifstream fin;
Fin.open(“second.txt”);
Ofstream fout; While(fin)
Fout.open(“second.txt”); {
Fout<<“united kingdom”; Fin.getline(line,N);
Fout<<“india”; Cout<<line;
Fout.close(); }
Fin.close();
Fout.open(“third.txt”); Fin.open(“third.txt”);
Fout<<“london”; While(fin)
Fout<<“new delhi”; {
Fout.close(); fin.getline(line,N);
Cout<<line;
}
Fin.close();
Return 0;

OUTPUT: OPEN A FILE “SECOND.TXT” THEN


} DISPLAY STRING “UNITED KINGDOM
AND INDIA”INTO THAT FILE AND OPAN ANOTHER FILE “THIRD .TXT” THEN DISPLAY
STRING “LONDON AND NEW DELHI” AFTERBY THAT OPEN BOTH FILES AND READ301
ZIA AKBAR
LINES FROM THESE FILE TO YOUR PROGRAM.
Using open function with
file modes
• The open function can take two arguments, the second
one for specifying the file mode and the first one is file
name.

• The general form of open function with two arguments


as follows
– stream-object.open(“file name”,mode);
the mode specifies the purpose for which the file is
opened.

When we are using open function without second


argument then compiler use the default values.{ios::in
for ifstream, ios::out for ofstream}

BY ZIA AKBAR 302


Modes File modes
Meaning

Ios::in Open for input operation

Ios::out Open for output operation

Ios::binary Open in binary mode

Ios::ate Set the initial position at the end of file.


If position is not set then position will be
beginning
Ios::app All output operations are performed at
the end of the file. appending the content
to current content of the file.
Ios::trunc If the file opened for output operation
already existed before, its previous
content is deleted and replaced by new
BY ZIA AKBAR 303
one.
EXAMPLE TO SHOW USE OF FILE MODE
#include<fstream.h>
Cin>>firstname>>second
#include<iostream.h> name>>age;
#include<conio.h> Student
Int main <<firstname<<secondna
{ char firstname[20],lastname[20]; me<<age;
int age; Student.close();
char filename[20]; Ifstream students(filename,
clrscr(); ios::in);
Cout<<“enter the file name you want Studnts>>firstname>>lastna
to open”; me>>age;
Cin>>filename; Cout<<“first name”
<<firstname;
Ofstream student;
Cout<<“last name”
Student .open(“filename”,ios::out); <<lastname;
Cout<<“enter your first name, Cout<<“age”<<age;
second name and age”;
Getch();
}
BY ZIA AKBAR 304
File pointers and their
manipulations
• Each file has two associated pointers known as the file
pointers.
• One of them is called the input pointer(get pointer) and the
other is called the output pointer(put pointer).

• We use these pointers to move through the files while


reading/writing.

• The input pointer is used for reading the contents of a


given location and the output pointer is used for writing to
a given file location.

BY ZIA AKBAR 305


• When a file is open in read mode, the input pointer is
automatically set at the beginning so that we can read
from start.

• When we open a file in writing mode, the existing contents


are deleted and the output pointer is set to the beginning.

• When we want to add some data into existing data of a file,


the file is opened in “append” mode.

BY ZIA AKBAR 306


Functions for manipulation
of file pointers
• Seekg() moves get pointer(input pointer) to a
specified location.
• Seekp() moves put pointer(output pointer)
to a specified location.
• Tellg() gives the current position of the get
pointer.
• Tellp() gives the current positions of the put
pointer.
• Infile.seekg(10);
• Statement moves the file pointer to the byte
number 10 BY ZIA AKBAR 307
• Specifying the offset:
• Seekg(offset,refposition);
• Seekp(offset,refposition);
1.The offset represents the number of bytes
the file pointer is to be moved from the
location specified by the parameter.
2.the refposition takes one of the following
1. Ios::beg start of the file
2. Ios::cur current position of the pointer
3. Ios::end end of the file

BY ZIA AKBAR 308


Sequential input and output
operations
• The file stream provide a set of
functions put(), and get() to handle a
single character at a time.
• The put() function write a single
character to the associated stream.
• The get() function reads a single
character from the associated stream.

BY ZIA AKBAR 309


Use of get and put functions
#include<iostream.h>
#include<fstream.h>
#include<string.h>
Int main()
{
char string[80];
Cout<<“enter a string\n”;
Cin>>string;
Int len=strlen(string);
Fstream file;
File.open(“text”,ios::in|ios::out);
For(int i=0;i<len;i++)
File.put(string[i]);
File.seekg(0);
Char ch;
While(file)
{
file.get(ch);
Cout<<ch;}
Return 0;
}
OUTPUT: IT WILL DISPLAY SINGLE CHARACTER FROM PROGRAM TO FILE AND AFTER THAT READ
SINGLE CHARACTER FROM FILE

BY ZIA AKBAR 310


this pointer
• Every object in C++ has access to its own
address through an important pointer called
this pointer.
• The this pointer is an implicit parameter to all
member functions. Therefore, inside a member
function, this may be used to refer to the
invoking object.
• Friend functions do not have a this pointer,
because friends are not members of a class.
Only member functions have a this pointer.

BY ZIA AKBAR 311


BY ZIA AKBAR 312

You might also like