Date post: | 03-Mar-2017 |
Category: |
Engineering |
Upload: | umesh-nikam |
View: | 105 times |
Download: | 0 times |
1
Object Oriented Technology.4 IT 03-FOURTH SEM-IT
Subject Teacher Umesh V.Nikam.
2
Chapter 1: Introduction to Object Oriented Programming
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
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.
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
6
7
8
Object Oriented ProgrammingCHARACTERISTICS: 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.
9
Fundamentals of OOPsObject: 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
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
12
Inheritance & Polymorphism
13
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.
15
Benefits of OOPS
Applications of OOP
16
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.
18
Comment: Single Line
Multiline
A Simple C++ Program Structure
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.
NAMESPACEo 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.o using and namespace are keywords.
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
cin statemento 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/Oo cin>> number1<<number2.o cout<<“Number1=”<<number1;o cout<<“Number2=”<<number2;o cout <<“Number1=”<<number1<<“Number2=”<<number2;o cout <<“Number1=”<<number1 <<“,”<<“Number2=”<<number2 <<“\
n”;
22
Simple C++ Program.
23
Class Declaration
24
Creating Object
item x;Accessing Class Members
x.getdata(100,75.5);x.putdata();x.number=100; X
25
Defining Member Function1-Inside Class 2-Outside Class
26
27
Array of OBJECT
28
Object as Function Argument
OUTPUT
29
Constructor
30
Characteristics of Constructor
31
Parameterised Constructor
Creating Object
32
Example Constructor
33
Constructor Overloading
Creating Objects
34
Copy Constructor It is used to declare & initialize an object from another object
Static Data Members1.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.
Static Member Function1.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
37
Unit 2: Operator Overloading
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
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
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.
Where return type is type of value returned by a operation. op is operator.
Overloading Unary Operator
Output
Overloading Binary Operator
Output
How it works ?
Pitfalls of Operator Overloading:Use similar meanings
Use similar syntaxShow restraintAvoid ambiguityNot all operators can be overloaded
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;
}
Output100 -Address of var1102 –Address of var2
Output1122
int main( ){
int var1 = 11;int var2 = 22;int* ptr; ptr = &var1; cout << *ptr <<
endl; ptr = &var2; cout << *ptr <<
endl; return 0;
}
Pointer Arithmeticint 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:5675221890
VALUE OF PTR 56VALUE OF PTR++ 75VALUE OF PTR-- 56VALUE OF PTR+2 22VALUE OF PTR-1 75VALUE OF PTR+=3 90VALUE OF PTR-=2 22
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++;}
}
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;
}
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<<endlptr = &Subtract; ptr ( 3,2 );return 0;
}
OUTPUTi + j =3i – j =1
Type Conversionint m;float x=3.14159;m=x;What about user defined data
type???V3=V1+v2
Type Conversion1.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
Type Conversion2.Class to Basic Type
A CONSTRUCTOR DOES NOT SUPPORTA 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 member2-It must not specify return type3-It must not have any argument
Type Conversion3.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;
Type Conversion
SUMMARY
new & delete operatorNew 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.
new operator
It automatically computes the size of data object. We need not use the operator sizeofIt automatically returns the correct pointer type, so no need to use typecast.It is possible to initialize the object while creating memory spaceNew & delete can also be overloaded.
Advantages of new over malloc( )
delete operatorWhen 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
String ClassString is a sequence of charactersC++ does not support built in string typeANSI standard provides a new class called as stringString class is very large & includes many constructors,member functions & operators
String ConstructorsString( ) For creating empty stringString(const char *str ) For creating a string object from null terminated stringString(const string &str) For creating string object from other string object
String ClassFunctions supported by string class
Creating String object String s1; //using constructor with no
argumentString s2(“XYZ”); //using one argument constructorS1=s2; //Assigning a string objectS3= “abc” + s2; // Concatinating stringCin >> 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
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;
}
OUTPUTS1=NewNow s1=standard c++S4=Standard c++Enter a string Information TechnologyNow s4= InformationFinally s1=New Delhi
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;}
OUTPUTOriginal Strings are:S1:12345S2:abcde
Modified s1=1234abcde5Now s1=12345
Now s2=a12345e
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;
}
OUTPUTSTRING CONTAINS:ONE TWO THREE FOUR
TWO Found at:4
T Found at:4 R Found last at:17
Substring: TWO
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 ChristmasHappy New year
Merry Christmas Happy New year
64
Unit 3: Inheritance in c++
65
Our goals: Derived class & base class Derived class constructors Function overloading Class hierachies Public & private inheritance Multiple inheritance containership: classes within
classes
66
InheritanceThe 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
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
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
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
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
Private InheritanceClass 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( ); Wrongd.mul( );d.show_a( ); Wrongd.display( );
d.b=20; Wrongd.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;
}
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.
Visibility of Inherited members
Multilevel InheritanceAssume 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( );}
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 111Enter Marks 70 80
Roll No = 111
Marks in Sub 1= 70Marks in Sub 2= 80
TOTAL= 150
Multiple Inheritance
76
Rewrite earlier program using multiple inheritance for the diagram shown below.
General Format
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 111Enter Marks 70 80
Roll No = 111
Marks in Sub 1= 70Marks in Sub 2= 80
TOTAL= 150
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 ;}
79
Hierarchical Inheritance
Write a program for hierarchical inheritance shown as in below diagram.
80
Hybrid InheritanceThere 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
Function OverloadingFunction 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
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;} ;
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 111Enter Name SACHIN
Roll No = 111Name= SACHIN
84
Constructors in Derived ClassWhen 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
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:
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 ;
}
OUTPUTbeta
initializedalpha
initializedgamma
initialized
X = 5Y =10.75M = 20N = 30
88
Chapter 4: Virtual Function Concept
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
90
Rules for Virtual Functions
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
Pure virtual functionsPure virtual functions are functions with no defination.They start with keyword virtual & ends with = 0Syntax 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; //ErrorBase *ptr;Derived d;ptr = &d;ptr ->show( );return 0;
}
93
Virtual base classes
94
Friend FunctionsPrivate 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-
95
Friend Functions
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
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 ;
elsecout<< 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
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
Assignment & Copy initializationCopy 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 = I1Will 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
OUTPUTid of A: 100id of B: 100id of C: 100id of D: 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.
101
Chapter 6: Template & Exception Handling
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
Exception HandlingErrors other than logical or syntactical errors known as EXCEPTIONSExceptions occurs at runtime.C++ exception handling mechanism is built upon three keywords namely try, catch and throwtry 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.
104
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 15RESULT=4
OUTPUT
Enter values of a&b:
10 10Exception Caught:
0
106
Throwing & catching mechanismExceptions can be thrown as throw( exception ); throw exception ;throw ;When an exception is thrown it is immediately caught by catch blockCatch block can be written as-
Catch(type arg) {
//statements }
107
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
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
# 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
# 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
# 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
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
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
ContainersContainers 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
Sequence containersSequence 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-vector2-list3-deque
117
Associative containersAssociative containers are designed to support direct access to elements using key.They are not sequential.There are four types of associative containers-1-set2-multiset3-map4-multimapAll 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
Derived containersSTL provides three derived containers they are-1-stack2-que3-priority queThey 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
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 iteratingThere are five types of iterators & must be used with different types of containers..Only sequence & associative containers traverse with iterators.
120
Function ObjectsFunction 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.
121
122
Chapter 5: Stream & File in C++
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
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 withoutstring str2 = “Delhi”; // embedded spaces
ofstream outfile(“fdata.txt”); //create ofstream objectoutfile << ch //insert (write) data<< j<< ‘ ‘ //needs space between numbers<< d<< str1<< ‘ ‘ //needs spaces between strings<< str2;cout << “File written\n”;return 0;
}
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 itinfile >> ch >> j >> d >> str1 >> str2;cout << ch //display the data<< j<< d<< str1<< str2 << endl;return 0;
}
126
Strings with embedded blanks(Writing File)
#include <fstream> //for file I/Ousing 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 hand\n”;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
Strings with embedded blanks(Reading File)
#include <fstream> //for file functions#include <iostream>using namespace std;
int main(){
const int MAX = 80; //size of bufferchar buffer[MAX]; //character bufferifstream infile(“TEST.TXT”); //create file for inputwhile( ! infile.eof() ) //until end-of-file{
infile.getline(buffer, MAX); //read a line of textcout << buffer << endl; //display it
}return 0;
}
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 written\n”;}
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
Binary I/O #include <fstream>#include <iostream>using namespace std;const int MAX = 100; //size of bufferint buff[MAX]; //buffer for integersint 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 fileifstream is(“edata.dat”, ios::binary);is.read( reinterpret_cast<char*>(buff), MAX*sizeof(int) );for(j=0; j<MAX; j++) //check dataif( buff[j] != j ){
cout << “Data is incorrect\n”; return 1;
}cout << “Data is correct\n”;return 0;
}
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
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
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 personpers.showData(); //read another personfile.read( reinterpret_cast<char*>(&pers), sizeof(pers) );
}cout << endl;return 0;
}
133
Overloading cin & cout operator XX
134
Stream class hierarchyWhat 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.
135
Stream class hierarchyWhat is stream? Describe stream class hierarchy with advantages?
136
Memory as stream objectDescribe 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 ostream3-For input to a memory there is istrstream derived from istream.4-For input & output there is strstream derived from iostream
137
Memory as stream object
#include <strstream> #include <iostream>#include <iomanip> using namespace std;const int SIZE = 80; int main(){
char ch = ‘x’; int j = 77;double d = 67890.12345;char str1[] = “New”;char str2[] = “Delhi”;char membuff[SIZE]; ostrstream os(membuff, SIZE); os << “ch=” << ch << endl << “j=” << j << endl << setiosflags(ios::fixed) << setprecision(2)<< “d=” << d << endl<< “str1=” << str1 << endl<< “str2=” << str2 << endl<< ends;cout << membuff; return 0;
}
OUTPUT:ch=x\nj=77\nd=67890.12\nstr1=New\nstr2=Delhi\n\0
138
DifferentModes of opening a fileList & explain different modes of opening a file?
139
Command line argument
#include <iostream>using namespace std;
int main(int argc, char* argv[] ){
cout << “\nargc = “ << argc << endl;for(int j=0; j<argc; j++) cout << “Argument “ << j << “ = “ << argv[j] << endl;return 0;
}
a sample interaction with the program:
C:\C++BOOK\Chap12>comline uno dos tres
OUTPUTargc = 4Argument 0 = C:\CPP\CHAP12\COMLINE.EXEArgument 1 = unoArgument 2 = dosArgument 3 = tres