3. 3
Our goals:
Introduction to procedural,modular,object oriented
and generic programming techniques.
Limitations of procedural programming.
Need of object oriented programming.
Fundamentals of object oriented programming.
Object and classes in c++.
Declaring & using classes.
Constructors.
Object as function argument.
Copy constructor.
Static class data.
Array of objects.
4. 4
Procedure Oriented Programming
Conventional programming using high level languages such
as COBOL,FORTRAN and C is known as procedure
oriented programming.
Procedure oriented programming is about writing a list of
instructions and organizing these instructions into groups
known as FUNCTIONS.
Problem is viewed as sequence of things to be done such
as reading,calculating,printing etc.
5. Characteristics:
Number of functions are written to accomplish task.
Emphasis is on doing things.
Large programs are divided into smaller known as
function
Most of the functions share global data.
Data move openly around the function from system
to system.
Functions transform data from one form to another.
It does not model real world problem very well.
Employs top-down approach in program design.
5
8. 8
Object Oriented Programming
CHARACTERISTICS:
Emphasis is on data rather than procedure.
Programs are decomposed into entities known as
OBJECT.
Functions are tied together in data structure.
Data is hidden & cannot be accessed by external
functions.
Objects communicate through functions.
New data & functions can be added whenever
necessary.
Follows bottom up approach in program design.
10. Fundamentals of OOPs
Object:
Basic Run time entities that may represent a
person,a place, a bank account or any item.
Each object contain data and functions to
manipulate data.
10
11. Classes:
Class is collection of data members and
member functions.
Once the class is defined, any number of
objects can be created from it.
It is a blueprint for an object.
Class is also a collection of objects of similar
data type.
Eg-If Fruit has been defined as class then-
Fruit mango;
Create object mango belonging to class Fruit.
11
14. Dynamic Binding
Means code associated with given function is not
known until time of call at runtime.
Linking with code at runtime.
Also called as Late –Binding.
Ex-draw() in above figure.
14
Message Passing
Message passing involves specifying name of
object,function & information to be sent.
17. 17
What is C++
It is an object oriented programming language.
Developed by Bjarne Stroustrup at AT&T Bell
Laboratories in Murray Hill,New Jersey,USA in 1980’s.
C++ is an extension of c with class construct features
of simula67.
The idea of C++ comes from the C increment
operator ++.
In 1997. the ANSI/ISO standards committee
standardized the changes and added several new
features to the language specification.
19. 19
A Simple C++ Program Structure
IOSTREAM FILE
o This directive causes preprocessor to add
contents of iostream file to the program.
o Contains declaration for cout and << .
o Should be included at the beginning of
every program.
o Use iostream.h if compiler does not
support ANSI C++ features.
NAMESPACE
o Defines scope for the identifiers used in
the program.
o std is the namespace where ANSI C++
standard class libraries are defined.
o Bring all identifiers defined in std to
current global scope.
20. 20
A Simple C++ Program Structure
COUT statement
o cout is standard o/p stream in c++ which
represents screen.
o << is called insertion or put to operator.
o Inserts contents of variable on its right to the
object on its left.
o cout << number
Return type of main()
Can we use printf() ???
21. 21
cin statement
o cin is standard i/p stream in c++ which represents keyboard.
o >> is called extraction or get from operator.
o Extracts value from keyboard & assign to the variable on its right.
CASCADING I/O
o cin>> number1<<number2.
o cout<<“Number1=”<<number1;
o cout<<“Number2=”<<number2;
o cout <<“Number1=”<<number1<<“Number2=”<<number2;
o cout <<“Number1=”<<number1 <<“,”<<“Number2=”<<number2 <<“n”;
35. Static Data Members
1.Initialized to zero when first object
of class is created. NO OTHER
INITIALIZATION IS PERMITTED
2.Only one copy is created & is shared
by all the objects of a class.
OUTPUT
3.Visible only within a class, but it’s
lifetime is the entire program.
36. Static Member Function
1.Can have access to only other static
members declared in same class.
2.Can be called using the class name
Class name::Function name;
OUTPUT
WRONG
38. 38
Our goals:
C++ String class
Operator Overloading: Unary & Binary Operator.
Pitfalls of operator overloading
Data Conversion
Pointers & arrays
Pointers & function
New & delete operators
Pointers for object
39. 39
Operator Overloading
Giving additional meaning to operator called as operator
overloading.
General form of function is:
Where
return type is type of value returned by a operation.
op is operator to be overloaded.
40. 40
Rules for Overloading operator
Only existing operators can be overloaded.
We cannot change basic meaning of operator.
Overloaded operators follow syntax rules of original operator.
Unary operator overloaded by means of member
function,takes no argument & return no explicit value,but
overloaded by friend function takes one reference argument.
Binary operator overloaded by means of member
function,takes one argument & overloaded by friend function
takes two explicit argument.
There are some operators that cannot be overloaded.
43. Pitfalls of Operator Overloading:
Use similar meanings
Use similar syntax
Show restraint
Avoid ambiguity
Not all operators can be overloaded
44. Pointers
int *ptr;Declaration
It is a variable which stores address of another variable
int main( )
{
int var1 = 11;
int var2 = 22;
int* ptr;
ptr = &var1;
cout << ptr << endl;
ptr = &var2;
cout << ptr << endl;
return 0;
}
Output
100 -Address of var1
102 –Address of var2
Output
11
22
int main( )
{
int var1 = 11;
int var2 = 22;
int* ptr;
ptr = &var1;
cout << *ptr << endl;
ptr = &var2;
cout << *ptr << endl;
return 0;
}
45. Pointer Arithmetic
int main( )
{
int num[ ]={ 56,75,22,18,90 };
int *ptr;
int i;
cout<<“Array Elements Are:”<<endl;
for(i=0;i<5;i++)
{
cout<<num[ i ] <<endl;
}
ptr=num;
cout<<“VALUES OF PTR”<<*ptr;
ptr++;
cout<<“VALUES OF PTR++”<<*ptr;
ptr--;
cout<<“VALUES OF PTR--”<<*ptr;
ptr = ptr+2;
cout<<“VALUES OF PTR+2”<<*ptr;
ptr = ptr-1;
cout<<“VALUES OF PTR-2”<<*ptr;
ptr += 3;
cout<<“VALUES OF PTR+=3”<<*ptr;
ptr -= 2;
cout<<“VALUES OF PTR-=2”<<*ptr;
return 0;
}
Output
Array Elements Are:
56
75
22
18
90
VALUE OF PTR 56
VALUE OF PTR++ 75
VALUE OF PTR-- 56
VALUE OF PTR+2 22
VALUE OF PTR-1 75
VALUE OF PTR+=3 90
VALUE OF PTR-=2 22
46. Pointers with arrays
//A Program to sum all elements of array
int main( )
{
int number [ 50 ] *ptr;
int n,i, sum=0;
cout<<“Enter the values:”<<endl;
for( i=0;i<5;i++)
{
cin>>number[ i ] ;
}
ptr=number;
for( i=0;i<5;i++)
{
sum=sum + *ptr;
ptr++;
}
cout<<“Sum of array element is: ”<<sum;
return 0;
}
//Sum of even Numbers:
for( i=0;i<5;i++)
{
if( *ptr%2==0)
{
sum=sum+*ptr;
ptr++;
}
}
47. Pointers to object #include <iostream>
using namespace std;
class Person
{
char name [30];
int age;
public:
void getdata ( );
void display ( );
};
void Person :: getdata ( )
{
cout<<”Enter Name:n”;
cin>>name;
cout<<”Enter Age:n”;
cin>>age;
}
void Person :: display( )
{
cout<<” Name: ”<<name;
cout<<”Age: ”<<age;
}
int main( )
{
Person p;
p.getdata ( );
p.display ( );
Person *ptr=&p;
ptr->getdata( );
ptr->display( );
return 0;
}
48. Pointers to functions
#include <iostream>
using namespace std;
typedef void (*FunPtr) (int a, int b);
void Add(int i, int j )
{
cout<<”i + j =”<<i + j;
}
void Subtract(int i, int j )
{
cout<<”i – j =”<<i - j;
}
int main( )
{
FunPtr ptr;
ptr = &Add;
ptr ( 1,2 );
cout<<endl
ptr = &Subtract;
ptr ( 3,2 );
return 0;
}
OUTPUT
i + j =3
i – j =1
50. Type Conversion
1.BASIC TO CLASS TYPE
A CONSTRUCTOR IS USED
Converts name1 from char* type to string type
& then assign string type value to the object s1
51. Type Conversion
2.Class to Basic Type
A CONSTRUCTOR DOES NOT SUPPORT
A CASTING OPERATOR FUNCTION IS USED
Operator double() converts class
object from vector to type double
Should satisfy following conditions:
1-It must be a class member
2-It must not specify return type
3-It must not have any argument
52. Type Conversion
3.One Class to another class type
Conversion between object of different class can be carried out by
either a constructor or conversion function.
objX = objY;
54. new & delete operator
New is used to allocate memory dynamically.
Delete is used to free dynamically allocated memory.
Since these operators manipulate memory on free store they are also
known as free store operators.
New operator can be used to create object of any type.
55. new operator
It automatically computes the size of data object. We need not use
the operator sizeof
It automatically returns the correct pointer type, so no need to use
typecast.
It is possible to initialize the object while creating memory space
New & delete can also be overloaded.
Advantages of new over malloc( )
56. delete operator
When data object is no longer needed, it is destroyed to release the
memory space for reuse using delete operator.
Delete is used to free dynamically allocated memory.
If you want to free dynamically created array
57. String Class
String is a sequence of characters
C++ does not support built in string type
ANSI standard provides a new class called as string
String class is very large & includes many constructors,member
functions & operators
String Constructors
String( ) For creating empty string
String(const char *str ) For creating a string object from null terminated
string
String(const string &str) For creating string object from other string
object
59. Creating String object
String s1; //using constructor with no argument
String s2(“XYZ”); //using one argument constructor
S1=s2; //Assigning a string object
S3= “abc” + s2; // Concatinating string
Cin >> s1; //Reading from keyboard(One word)
getline(cin, s1); //Reading from keyboard a line of text
Using cin operator we can read only one word of a string while the
getline( ) function permits us to read a line of text containing embedded blanks
60. Creating String object
#include <iostream>
#include<string>
Using namespace std;
int main( )
{
string s1;
string s2(“New”);
string s3(“Delhi”);
s1=s2;
cout<<“S1=”<<s1;
s1=“Standard c++”;
cout<<“Now S1=”<<s1;
string s4(s1);
cout<<“S4=”<<s4;
cout<<“Enter a string”<<endl;
cin>>s4;
cout<<“Now S4=”<<s4;
s1=s2 + s3;
cout<<“Finally S1=”<<s1;
return 0;
}
OUTPUT
S1=New
Now s1=standard c++
S4=Standard c++
Enter a string
Information Technology
Now s4= Information
Finally s1=New Delhi
61. Modifying String object
#include <iostream>
#include<string>
Using namespace std;
int main( )
{
string s1(“12345”);
string s2(“abcde”);
cout<<“Original Strings are:”;
cout<<“S1=”<<s1<<endl;
cout<<“S2=”<<s2<<endl;
s1.insert(4,s2);
cout<<“Modified S1=”<<s1;
s1.erase(4,5);
cout<<“Now S1=”<<s1;
s2.replace(1,3,s1);
cout<<“Now S2=”<<s2;
return 0;
}
OUTPUT
Original Strings are:
S1:12345
S2:abcde
Modified s1=1234abcde5
Now s1=12345
Now s2=a12345e
62. Modifying String object
#include <iostream>
#include<string>
Using namespace std;
int main( )
{
string s(“ONE TWO THREE FOUR”);
cout<<“STRING CONTAINS:”;
for(int i=0;i<s.length();i++)
{
cout << s.at(i);
}
int x1=s.find(“TWO”);
cout<<“TWO Found at:”<<x1;
int x2= s.find_first_of(‘T’);
cout<<“T Found at:”<<x2;
int x3= s.find_last_of(‘R’);
cout<<“R Found last at:”<<x3;
cout<<“Substring:”<<s1.substr(x1,3);
return 0;
}
OUTPUT
STRING CONTAINS:
ONE TWO THREE FOUR
TWO Found at:4
T Found at:4
R Found last at:17
Substring: TWO
63. Concatenation of two string using operator overloading
#include <iostream>
#include<string>
Using namespace std;
Class string
{
char str [50];
public:
string( )
{
strcpy (str, “ ”);
}
string( char s[ ])
{
strcpy (str, s);
}
void display( )
{
cout<<str<<endl;
}
string operator +( string ss)
{
string temp;
strcpy(temp.str, str);
strcat(temp.str,ss.str);
return temp;
}
};
int main( )
{
string s1=“n Merry Christmas”;
string s2=“ Happy New year“;
string s3;
s1.display( ); s2.display( ); s3.display( );
s3=s1+s2;
S3.display( );
return o;
}
OUTPUT
Merry Christmas
Happy New year
Merry Christmas Happy New year
65. 65
Our goals:
Derived class & base class
Derived class constructors
Function overloading
Class hierachies
Public & private inheritance
Multiple inheritance containership: classes within classes
66. 66
Inheritance
The mechanism of creating a new class from an old one is called
inheritance.
Old class is called as BASE class & new one is called DERIVED
class or SUBCLASS
DERIVED class inherits some or all features from the base class
A class can also inherit properties from more than one class
67. 67
Types of Inheritance
Derived class with only one base class
is called SINGLE inheritance
Derived class with only more than one
base class is called MULTIPLE
inheritance
68. Types of Inheritance
BASE class inherited by more than
one DERIVED class called
HIERARCHICAL inheritancce
The process of deriving a class from
another derived class is known as
MULTILEVEL inheritancce
69. Defining Derived class & Inheritance
Class ABC : private XYZ
{
members of ABC
};
Class ABC : public XYZ
{
members of ABC
};
Class ABC : XYZ
{
members of ABC
};
Class derived class name : visibility-mode base class
name
{
members of derived class
};
GENERAL FORMAT
Visibility is optional.
Default visibility is private.
When base class is privately inherited,
public members of base class become
private members of derived class &
therefore no member of base class is
accessible to object of derived class.
When base class is publicly inherited,
public members of base class become
public members of derived class &
therefore they are accessible to object
of derived class.
In both the cases private members are
not inherited
70. Defining Derived class & Inheritance
Class B
{
int a;
public :
int b;
void get_ab( );
int get_a( );
void show_a( );
} ;
void B :: get_ab( )
{
a=5; b=10;
}
int B :: get_a( )
{
return a;
}
Void B :: show_a( )
{
cout<< “a=”<<a;
} ;
Class D: public B
{
int c;
Public :
void mul( );
void display( );
} ;
Void D :: mul( )
{
c = b * get_a( );
}
Void D :: display( )
{
cout<<“a=”<<get_a( )<<endl;
cout<<“b=”<< b <<endl;
cout<<“c=”<< c <<endl;
}
int main( )
{
D d;
d.get_ab( );
d.mul( );
d.show_a( );
d.display( );
d.b=20;
d.mul( );
d.display( );
return 0;
}
OUTPUT
71. Private Inheritance
Class B
{
int a;
public :
int b;
void get_ab( );
void get_a( );
void show_a( );
} ;
void B :: get_ab( )
{
a=5; b=10;
}
int B :: get_a( )
{
return a;
}
Void B :: show_a( )
{
cout<< “a=”<<a;
} ;
Class D: private B
{
int c;
Public :
void mul( );
void display( );
} ;
int main( )
{
D d;
d.get_ab( ); Wrong
d.mul( );
d.show_a( ); Wrong
d.display( );
d.b=20; Wrong
d.mul( );
d.display( );
return 0;
}
OUTPUT
void D :: mul( )
{
get_ab( );
c = b * get_a( );
}
void D :: display( )
{
show_a( );
cout<<“b=”<< b <<endl;
cout<<“c=”<< c <<endl;
}
72. Making Private member Inheritable
How ??? C++ supports third visibility
modifier “PROTECTED”
A member declared as
protected is accessible by the
member function within its class
& any class immediately derived
from it.
Protected member inherited in
public mode becomes protected
in derived class & therefore is
accessible by the member
function of derived class & can
be inherited further also.
Protected member inherited in
private mode becomes private in
derived class & therefore is
accessible by the member
function of derived class but it is
not available for further
inheritance.
74. Multilevel Inheritance
Assume that a test result of a batch of students is stored in three
different classes. Class Student stores rollno, class test stores the marks
obtained in two subjects & class result contains total marks obtained in
test.The class result can inherit the details of marks obtained in test & the
rollno of students through multilevel inheritance.
Student
{
Data Member:
rollno;
MemberFunction:
getnumber( );
putnumber( );
}
test
{
Data Member:
sub1,sub2;
MemberFunction:
getmarks( );
putmarks( );
}
result
{
Data Member:
total;
MemberFunction:
display( );
}
75. Class Student
{
protected :
int rollno;
public :
void getnumber( );
void putnumber( );
} ;
void Student :: getnumber( )
{
cout<<“Enter Roll No n”;
cin >> rollno;
}
Void Student :: putnumber( )
{
cout<<“Roll No=”<<
rollno;
}
Class test : public Student
{
protected :
float sub1, sub2;
public :
void getmarks( );
void putmarks( );
} ;
int main( )
{
result stud1;
stud1.getnumber( );
stud1.getmarks( );
stud1.display( );
return 0;
}
void test :: getmarks( )
{
cout<<“Enter Marks n”;
cin >> sub1 >> sub2;
}
Void test :: putmarks( )
{
cout<<“Marks in Sub 1=”<<sub1 ;
cout<<“Marks in Sub 2=”<<sub2 ;
}
Class result : public test
{
float total;
public :
void display( );
} ;
Void result :: display( )
{
total = sub1 + sub 2;
putnumber ( );
putmarks( );
cout << “TOTAL=” << total;
}
OUTPUT
Enter Roll No 111
Enter Marks 70 80
Roll No = 111
Marks in Sub 1= 70
Marks in Sub 2= 80
TOTAL= 150
77. Class Student
{
protected :
int rollno;
public :
void getnumber( );
void putnumber( );
} ;
void Student :: getnumber( )
{
cout<<“Enter Roll No n”;
cin >> rollno;
}
Void Student :: putnumber( )
{
cout<<“Roll No=”<<
rollno;
}
Class test
{
protected :
float sub1, sub2;
public :
void getmarks( );
void putmarks( );
} ;
int main( )
{
result stud1;
stud1.getnumber( );
stud1.getmarks( );
stud1.display( );
return 0;
}
void test :: getmarks( )
{
cout<<“Enter Marks n”;
cin >> sub1 >> sub2;
}
Void test :: putmarks( )
{
cout<<“Marks in Sub 1=”<<sub1 ;
cout<<“Marks in Sub 2=”<<sub2 ;
}
Class result : public student,
public test
{
float total;
public :
void display( );
} ;
Void result :: display( )
{
total = sub1 + sub 2;
putnumber ( );
putmarks( );
cout << “TOTAL=” << total;
}
OUTPUT
Enter Roll No 111
Enter Marks 70 80
Roll No = 111
Marks in Sub 1= 70
Marks in Sub 2= 80
TOTAL= 150
78. 78
Ambiguity Resolution
Class P : public M, public N
{
public :
void display( )
{
M :: display( );
}
}
int main( )
{
P obj;
obj.display( ) ;
obj.N :: display() ;
return 0 ;
}
80. 80
Hybrid Inheritance
There could be a situations where we need to apply two or more types
of inheritance to design a program. Hybrid inheritance is used for
such situations
81. 81
Function Overloading
Function having same name but different parameters which perform
different tasks known as function overloading. It is also known as
function polymorphism.
#include<iostream>
Using namespace std;
Class Base
{
public :
int volume (int s )
{
cout<<“Volume of cube=”<<s*s*s ;
}
double volume (double r, int h )
{
cout<<“Volume of cylinder=”<<3.14*r*r*h
;
}
long volume (long l, int b, int h )
{
cout<<“Volume of box=”<<l*b*h ;
}
} ;
int main( )
{
Base b;
b.volume( 10 );
b.volume( 2.5, 8 );
b.volume( 100L, 75, 15 );
return 0;
}
82. 82
Aggregation: Classes within classes (CONTAINERSHIP)
Aggergation is called as has- a relationship.
Agregation may occur when one object is attribute of another class.
An object can be a collection of many other objects.
A class can contain object of other class as its member.
This kind of relationship is called as containership or nesting of
classes
Class A
{
} ;
Class B
{
A objA;
} ;
83. Class Student
{
protected :
char name[20];
int rollno;
public :
void getdata( );
void putdata( );
} ;
void Student :: getdata( )
{
cout<<“Enter Roll No n”;
cin >> rollno;
cout<<“Enter Name n”;
cin >> name;
}
Void Student :: putdata( )
{
cout<<“Roll No=”<< rollno;
cout<<“Name=”<< name;
}
int main( )
{
result r;
r.display( );
return 0;
}
Class result
{
Student stud ;
public :
void display( );
} ;
Void result :: display( )
{
stud. getdata( );
stud. putdata( );
}
OUTPUT
Enter Roll No 111
Enter Name SACHIN
Roll No = 111
Name= SACHIN
84. 84
Constructors in Derived Class
When a base class have a constructor with one or more argument then
it is necessory to have a constructor in derived class & pass argument to
base class constructor.
When both the classes contains constructor then base class
constructor is executed first followed by a derived class constructor.
In multilevel & Multiple inheritance base classes are executed in the
order of their inheritance.
Constructors of derived class receives the entire list of values as its
arguments & passes them on to the base constructors in the order in
which they are declared in the derived class.
85. 85
The derived constructor contains two parts seperated by colon (:).
First part provides arguments passed to derived constructor &
second part lists function call to base constructors.
A(a1 , a2) invokes base constructor A( ) & B(b1 , b2) invokes another
base constructor B( ). D( ) may be invoked as follows:
86.
87. Class alpha
{
int x;
public :
alpha ( int i )
{
x=i;
cout<<“alpha initialized” ;
}
void show_x( )
{
cout<<“X=“<<x ;
}
} ;
Class beta
{
float y;
public :
beta ( float j )
{
y=j;
cout<<“beta initialized” ;
}
void show_y( )
{
cout<<“Y=“<<y ;
}
} ;
Class gamma : public beta, public alpha
{
int m, n ;
public :
gamma( int a, float b, int c, int d ):
alpha( a ), beta( b )
{
m = c;
n = d;
cout<<“Gamma Initialised n”;
}
Void show_mn( )
{
cout<<“M=” << m <<“n”;
cout<<“N=” << n <<“n”;
}
} ;
int main( )
{
gamma g( 5, 10.75, 20, 30);
g.show_x( );
g.show_y( );
g.show_mn( );
return 0 ;
}
OUTPUT
beta initialized
alpha initialized
gamma initialized
X = 5
Y =10.75
M = 20
N = 30
89. 89
Virtual Functions (RUNTIME POLYMORPHISM)
Here, we use pointer of base class to refer to all derived objects.
But, a base pointer even when it contains the object of derived
class, always executes function in base class.
This can be solved by declaring base function as virtual.
When we use same function name in both base class & derived
class, function in base class is declared as virtual.
When function is made virtual, c++ determines which function to
call at runtime based on the type of object pointed by base pointer
rather than type of the pointer.
Thus by making base pointer to point to different object we can
execute different versions of virtual functions
91. 91
Abstract class
Abstract class is a class which contains atleast one pure virtual
function.
Abstract classes are used to provide an interface to its subclasses
.
Classes inheriting abstract class must provide a body to pure
virtual functions, otherwise they will also become abstract class
Characteristics of abstract class
Object of abstract class cannot be created, but pointer &
references can be created.
Abstract class can have normal functions & variables along with
pure virtual functions.
Classes inheriting abstract class must provide a body to pure
virtual functions otherwise they also become abstract.
92. 92
Pure virtual functions
Pure virtual functions are functions with no defination.
They start with keyword virtual & ends with = 0
Syntax virtual void fun( )= 0;
Class Base
{
public :
virtual void show( )=0;
} ;
Class Derived : public Base
{
void show( )
{
cout<<“Show of Derived class ”
}
};
int main( )
{
Base obj; //Error
Base *ptr;
Derived d;
ptr = &d;
ptr ->show( );
return 0;
}
94. 94
Friend Functions
Private members cannot be accessed outside the class by
members of another class.
However their could be a situation where we would like, two
classes to share a particular function.
In such situations, c++ allows the common function to be made
friendly with both the classes
To make function as friendly to a class, simply declare this
function as friend as shown below-
96. 96
Class Sample
{
int a;
int b;
public :
void setvalue( )
{ a = 25 ;
b = 40 ;
}
friend float mean( Sample s ) ;
} ;
float mean( Sample s)
{
return float( s.a + s.b ) / 2.0;
}
int main( )
{
Sample x ;
x.setvalue( );
cout <<“Mean Value=” <<mean( x ) ;
return 0;
}
97. 97
Class ABC; //forward declaration
Class XYZ
{
int x;
public :
void setvalue( int i)
{ x = i ; }
friend void max( XYZ, ABC ) ;
} ;
Class ABC
{
int a;
public :
void setvalue( int i )
{ a = i ; }
friend void max( XYZ, ABC) ;
};
void max( XYZ m, ABC n)
{
if ( m.x >= n.a )
cout<< m.x ;
else
cout<< n.a ;
}
int main( )
{
ABC abc ;
abc.setvalue( 10 );
XYZ xyz ;
xyz.setvalue( 20 );
max( xyz, abc) ;
return 0;
}
Friend Functions FOR Two Classes
98. 98
this pointer
‘this’ pointer is a constant pointer that holds the memory address
of the current object.
‘this’ pointer is not available in static member functions as static
member functions can be called without any object.
Class Test
{
int x;
public :
void setX( int x )
{
this->x=x ;
}
void print( )
{
cout << “X=” << x <<endl ;
}
} ;
int main( )
{
Test obj ;
int x = 20;
obj.setX ( x ) ;
obj.print( );
return 0;
}
99. 99
Assignment & Copy initialization
Copy constructor is used to declare &
initialize an object from another object.
Ex-
Integer I2 ( I1 )
Another form of this statement is
Ex-
Integer I2 = I1
I2 = I1
Will not invoke the copy constructor, it
simply assigns the values of I1 to I2,
member by member, this is the task of
overloaded assignment operator
OUTPUT
id of A: 100
id of B: 100
id of C: 100
id of D: 100
100. 100
Que 1 : Explain the difference in operation between these two statements with example
Person P1 (Pq)
Person P1 = Pq ;
Que 2 : What is dynamic type information? Explain dynamic cast operator and
typed operator.
Que 3 : Explain what are abstract classes. Write a program having student as
an abstract class & create many derived classes such as IT, CSE, EXTC etc.
From student class. Create their object & process them.
102. 102
Our goals:
Function templates & class templates
Exception handling
Introduction to standard template library
Algorithms
Sequential containers, iterators.
Specialized iterators.
Associative containers function objects
103. 103
Exception Handling
Errors other than logical or syntactical errors known as EXCEPTIONS
Exceptions occurs at runtime.
C++ exception handling mechanism is built upon three keywords namely
try, catch and throw
try block surrounds the code which may generate an exception.
When an exception is detected it is thrown by using throw statement
in try block.
Keyword catch, catches exception thrown by throw statement.
105. 105
#include <iostream>
Using namespace std;
int main( )
{
int a,b;
cout<<“Enter values of a&b:” ;
cin >>a >> b;
int x= a- b ;
try
{
if( x!=0 )
{
cout <<“RESULT=” <<a/x ;
}
else
{
throw ( x );
}
}
catch ( int i )
{
cout<<“Exception Caught:” <<x ;
}
return 0;
}
OUTPUT
Enter values of a&b:
20 15
RESULT=4
OUTPUT
Enter values of a&b:
10 10
Exception Caught: 0
106. 106
Throwing & catching mechanism
Exceptions can be thrown as
throw( exception );
throw exception ;
throw ;
When an exception is thrown it is immediately caught by catch block
Catch block can be written as-
Catch(type arg)
{
//statements
}
108. 108
Void test( int x )
{
try
{
if ( x==1) throw x;
else
if( x==0) throw ‘x’ ;
else
if( x== -1) throw 1.0;
cout <<“End of try block”;
}
Catch ( char c)
{
cout<<“Caught character”;
}
Catch ( int m)
{
cout<<“Caught an integer”;
}
Catch ( double d)
{
cout<<“Caught double”;
}
Cout<< “End of try catch statements”;
int main( )
{
cout<< “X == 1”;
test (1);
cout<< “X == o”;
test (o);
cout<< “X == -1”;
test (-1);
cout<< “X == 2”;
test (2);
return 0;
}
109. 109
Templates
A template can be used to create a family of classes or functions.
For ex: a class template for an array class would enable us to create
arrays of various data types such as int array & float array.
Syntax of class template
110. 110
# include<iostream>
Using namespace std;
Class Test
{
int a ;
public :
Test ( int x)
{
a = x ;
}
void show( )
{
cout << “A=” <<a;
}
} ;
int main ( )
{
Test t1( 10);
t1.show( );
return 0;
}
# include<iostream>
Using namespace std;
template <class T >
Class Test
{
T a ;
public :
Test ( T x)
{
a = x ;
}
void show( )
{
cout << “A=” <<a;
}
} ;
int main ( )
{
Test <int> t1( 10);
Test <float> t2( 5.0);
t1.show( );
return 0;
}
111. 111
# include<iostream>
Using namespace std;
template <class T1, class T2 >
Class Test
{
T1 a ;
T2 b ;
public :
Test ( T1 x, T2 y)
{
a = x ;
b = y ;
}
void show( )
{
cout << “A & B=” <<a <<b;
}
} ;
int main ( )
{
Test <float, int> t1( 5.0,10);
Test <int, char> t2(100, ‘W’);
t1.show( );
t2.show( ) ;
return 0;
}
Template with multiple parameter
112. 112
# include<iostream>
Using namespace std;
template <class T>
void swap( T &x, T &y )
{
T temp = x ;
x = y ;
y = temp ;
}
Void fun (int m, int n, float a, float b)
{
cout<<“m & n before swap:”<<m<<n;
swap(m,n);
cout<<“m & n after swap:”<<m<<n;
cout<<“a & b before swap:”<<a<<b;
swap(a,b);
cout<<“a & b after swap:”<<a<<b;
}
int main ( )
{
fun( 100, 200, 11.22, 33.44 )
return 0;
}
Function template
113. 113
Standard Template Library
A set of general purpose classes & functions that could be used as a
standard approach for storing & processing of data.
Collection of these generic classes & functions is called as Standard
template library.
STL is large & complex.
STL is a part of standard c++ library defined in namespace std, we
therefore must use using namespace std:
Que: What is STL? How is it used? Explain following entities of STL
Containers & iterators.
114. 114
Components of STL
1-Containers:A container is an object which stores data. It is a way
data is organised in a memory.
Containers can be easily modified to store data.
2-Algorithms :It is a procedure that is used to process data
contained in container.
3-Iterators: It is an object that points to the element in a container.
We can use iterator to move through the contents of container.`
115. 115
Containers
Containers are objects that holds data.
STL defines 10 containers which are grouped into three categories –
QUE: What is container? List out its various types & explain each in
brief?
116. 116
Sequence containers
Sequence containers store elements in a linear sequence like a line as
shown in fig.
Each element is related to other by its position.
STL provides three types of sequence containers:
1-vector
2-list
3-deque
117. 117
Associative containers
Associative containers are designed to support direct access to
elements using key.
They are not sequential.
There are four types of associative containers-
1-set
2-multiset
3-map
4-multimap
All these containers store data in structure called tree which
facilitates fast searching, deletion & insertion.
They are very slow for random access & inefficient for sorting.
Set & multiset can store number of items & provides operation for
manipulating them using value as the key.
Multiset allows duplicate items while set does not.
Map & multimap are used to store pair of items called key & value.
Map allows only one key for a given value to be stored while multimap
permits multiple keys.
118. 118
Derived containers
STL provides three derived containers they are-
1-stack
2-que
3-priority que
They are also known as container adapters.
Derived conatiner do not support iterators & therefore we cannot use
them for data manipulation.
They support member function pop() & push() for deletion & insertion.
QUE:What is container? List out its various types & explain each in
brief?
119. 119
Iterators
Iterators behave like a pointer & are used to access container
elements.
They are used to traverse from one element to another & process is
known as iterating
There are five types of iterators & must be used with different types
of containers..
Only sequence & associative containers traverse with iterators.
120. 120
Function Objects
Function objects are used as arguments to certain algorithms.
They allow to customize operation of these algorithms.
Function object is a function that has been wrapped in a class so that
it looks like an object.
Predefined STL function object are defined in FUNCTIONAL header
file.
T indicates any class & variable x & y represents objects of class T
passed to function object as an argument.
123. 123
Disk file I/O
Most program need to save data to disk file & read it back in.
Working with disk file requires classes like ifstream for input,
ofstream for output & fstream for both input & output.
Objects of these classes can be associated with disk files, & we can
use their member functions to read & write to the files.
ifstream is derived from istream, fstream is derived from iostream, &
ofstream is derived from ostream.
Base class of all these is ios.
124. 124
Writing data to file
#include <fstream> //for file I/O
#include <iostream>
#include <string>
using namespace std;
int main()
{
char ch = ‘x’;
int j = 77;
double d = 6.02;
string str1 = “New”; //strings without
string str2 = “Delhi”; // embedded spaces
ofstream outfile(“fdata.txt”); //create ofstream object
outfile << ch //insert (write) data
<< j
<< ‘ ‘ //needs space between numbers
<< d
<< str1
<< ‘ ‘ //needs spaces between strings
<< str2;
cout << “File writtenn”;
return 0;
}
125. 125
Reading data from file
#include <fstream> //for file I/O
#include <iostream>
#include <string>
using namespace std;
int main()
{
char ch;
int j;
double d;
string str1;
string str2;
ifstream infile(“fdata.txt”); //create ifstream object
//extract (read) data from it
infile >> ch >> j >> d >> str1 >> str2;
cout << ch //display the data
<< j
<< d
<< str1
<< str2 << endl;
return 0;
}
126. 126
Strings with embedded blanks(Writing File)
#include <fstream> //for file I/O
using namespace std;
int main()
{
ofstream outfile(“TEST.TXT”); //create file for output
//send text to file
outfile << “I fear thee, ancient Mariner!n”;
outfile << “I fear thy skinny handn”;
outfile << “And thou art long, and lank, and brown,n”;
outfile << “As is the ribbed sea sand.n”;
return 0;
}
String containing blank space cannot be written directly.
To handle such string need to use a delimiter character & use a
getline( ) function to read them in.
127. 127
Strings with embedded blanks(Reading File)
#include <fstream> //for file functions
#include <iostream>
using namespace std;
int main()
{
const int MAX = 80; //size of buffer
char buffer[MAX]; //character buffer
ifstream infile(“TEST.TXT”); //create file for input
while( ! infile.eof() ) //until end-of-file
{
infile.getline(buffer, MAX); //read a line of text
cout << buffer << endl; //display it
}
return 0;
}
128. 128
Character I/O with put( ) & get( )
// Writing data to file
#include <fstream> //for file functions
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = “Time is a great teacher “ ;
ofstream outfile(“TEST.TXT”);
for(int j=0; j<str.size(); j++)
{
outfile.put( str[j] );
cout << “File writtenn”;
}
return 0;
}
// Reading data from file
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
char ch;
ifstream infile(“TEST.TXT”);
while( infile )
{
infile.get(ch);
cout << ch;
}
cout << endl;
return 0;
}
129. 129
Binary I/O #include <fstream>
#include <iostream>
using namespace std;
const int MAX = 100; //size of buffer
int buff[MAX]; //buffer for integers
int main()
{
for(int j=0; j<MAX; j++)
buff[j] = j;
// Writing to file
ofstream os(“edata.dat”, ios::binary);
os.write( reinterpret_cast <char*> (buff), MAX*sizeof(int) );
os.close();
for(j=0; j<MAX; j++)
buff[j] = 0;
// Reading from file
ifstream is(“edata.dat”, ios::binary);
is.read( reinterpret_cast<char*>(buff), MAX*sizeof(int) );
for(j=0; j<MAX; j++) //check data
if( buff[j] != j )
{
cout << “Data is incorrectn”;
return 1;
}
cout << “Data is correctn”;
return 0;
}
130. 130
Writing an Object to disk
#include <fstream>
#include <iostream>
using namespace std;
class person
{
protected:
char name[80];
short age;
public:
void getData()
{
cout << “Enter name: “; cin >> name;
cout << “Enter age: “; cin >> age;
}
};
int main()
{
person pers;
pers.getData();
ofstream outfile(“PERSON.DAT”, ios::binary);
outfile.write(reinterpret_cast<char*>(&pers), sizeof(pers));
return 0;
}
131. 131
Reading an Object From disk
#include <fstream>
#include <iostream>
using namespace std;
class person
{
protected:
char name[80];
short age;
public:
void showData()
{
cout << “Name: “ << name << endl;
cout << “Age: “ << age << endl;
}
};
int main( )
{
person pers;
ifstream infile(“PERSON.DAT”, ios::binary);
infile.read( reinterpret_cast<char*>(&pers), sizeof(pers) );
pers.showData();
return 0;
}
132. 132
I/O with multiple objects
#include <fstream>
#include <iostream>
using namespace std;
class person
{
protected:
char name[80];
int age;
public:
void getData()
{
cout << “n Enter name: “;
cin >> name;
cout << “ Enter age: “;
cin >> age;
}
void showData()
{
cout << “n Name: “ <<
name;
cout << “n Age: “ << age;
}
};
int main()
{
char ch;
person pers;
fstream file;
file.open(“GROUP.DAT”, ios::app | ios::out |ios::in |
ios::binary );
do {
cout << “nEnter person’s data:”;
pers.getData();
file.write( reinterpret_cast<char*>(&pers),
sizeof(pers) );
cout << “Enter another person (y/n)? “;
cin >> ch;
}
while(ch==’y’);
file.seekg(0);
file.read( reinterpret_cast<char*>(&pers), sizeof(pers) );
while( !file.eof() )
{
cout << “nPerson:”; //display person
pers.showData(); //read another person
file.read( reinterpret_cast<char*>(&pers),
sizeof(pers) );
}
cout << endl;
return 0;
}
134. 134
Stream class hierarchy
What is stream? Describe stream class hierarchy with advantages?
Stream is a flow of data. Stream is represented by an object of a
particular class.
Advantages:
1-Simplicity:
No use of formatting characters like %f
2-Can overload existing operators & function:
such as cin & cout, which makes programming easiear & error
free.
3-Best way to write a data to file & format in memory for use in text
input/output windows & other GUI elements.
136. 136
Memory as stream object
Describe with suitable example, uses of memory as a stream object?
1-When you need to format your output in a particular way you can use
memory as a stream object.
2-For output to a memory there is ostrstream derived from ostream
3-For input to a memory there is istrstream derived from istream.
4-For input & output there is strstream derived from iostream