Beruflich Dokumente
Kultur Dokumente
Course Objective To introduce the principles and concepts behind Object Oriented Programming To explain how complex scenarios can be handled easily using Object Oriented Technology
Digitech Technologies
Digitech Technologies
Digitech Technologies
Digitech Technologies
Engine
Digitech Technologies
Driving
Capacitor Resistor
Buffer
Reset B8
Inverter
Diode
AND Gate
Register
A Q1
ENB
Boolean Logic Gates Digital circuits built Central Processing unit built using basic using Boolean logic Built using complex electronic components gates digital circuits st Level abstraction) nd Level abstraction) rd level abstraction) (1 (2 (3 Digitech Technologies 6
Encapsulation Encapsulate = En + Capsulate En = In a Encapsulate = In a Capsule Encapsulation means localization of information of knowledge within an object. Encapsulation also means Information hiding Example: A cars dashboard hides the complexity and internal workings of its engine.
Digitech Technologies
Digitech Technologies
Digitech Technologies
Inherits
Wealth
Digitech Technologies
10
BusinessLoan
-InterestType : char -Term : char +GetInterestType() : char +SetInterestType() +GetTerm() : char +SetTerm()
Data additionally required for BusinessLoan. Common members inherited from base class
LargeBusinessLoan
-MoratoriumPeriod : int +GetMoratoriumPeriod() : int +SetMoratoriumPeriod()
Digitech Technologies
11
ElectricCar
-BatteryCapacity : float
HybridCar
Digitech Technologies
12
Address PropertyDetails
Has A
Part of
-PropertyHolderName : string -Address : Address -DocumentNumber : int +GetDocumentNumber() : int +SetDocumentNumber() +GetProperyHolderName() : string +SetPropertyHolderName() +GetAddress() : Address +SetAddress()
Has A
Part of
Digitech Technologies
-AddressLine1 : char -AddressLine2 : string -City : string -Zip : string -State : string +GetAddressLine1() : string +SetAddressLine1() +GetAddressLine2() : string +SetAddressLine2() +GetCity() : string +SetCity() +GetZip() : string +SetZip() +GetState() : string +SetState()
14
Digitech Technologies
17
(BEHAVIOR)
(STATE)
ak Do e (S w lo n) w
Digitech Technologies
Br
18
object
class
Class Student Name
Regn_No
setName()
Jodie R001
Daria R002
Jane R003
Brittany R004
setRegnNo() CalcMarks()
19
Digitech Technologies
Digitech Technologies
20
Shape +Draw()
Loan
-LoanAmount : double -InterestRate : float -Duration : int -CustomerID : int +GetInterestRate() : float +GetLoanAmount() : double +GetDuration() : int +GetCustomerID() : int +SetDuration() +SetLoanAmount() +SetInterestRate() +SetCustomerID() +Report()
Line
-... +Draw()
Rectangle
-... +Draw()
Circle
-... +Draw()
Octagon
-... +Draw()
Housing Loan
-InterestType : char +GetInterestType() : char +SetInterestType() +Report()
Digitech Technologies
22
Digitech Technologies
24
Digitech Technologies
25
Digitech Technologies
26
Basics of C++
C++ is an Object Oriented programming language It can be considered as a super set of C This enables backward compatibility Bjarne Stroustrup first invented C with Classes and then it was renamed to C++ in 1983. In 1997, ANSI/ISO standards committee standardized C++ Like C, C++ is also case sensitive.
C++ C
Digitech Technologies
27
Output 65 A 65 A
28
Digitech Technologies
29
Digitech Technologies
30
C++ comments
C++ is backward compatible with C C Style comments are also supported C Style comments are used to write function headers , file headers etc Example: /**************************************************** * This style of commenting is used for functions and files *****************************************************/ C++ style of comments are single line comments Any text after // is comment till the end of the line Example: // This is for single line comment fArea = fRadius * fRadius * PI ; // calculating area of Circle
Digitech Technologies 31
Control Structures
Control Structures are statements which changes the execution sequence of the program C++ supports all the control structures supported in C If, else if, else
switch case
for loop while loop do while
Digitech Technologies
32
::cout<<cout<<endl;
Digitech Technologies
34
Output 44 44 44
Digitech Technologies
35
Physical constant
Physical constants are provided sufficient memory space. A const declaration is taken as physical constant if the initial value is given at run-time.
Digitech Technologies 36
void abc(int a,int b) { cout << a << " " << b <<endl; }
Digitech Technologies
38
Output 90 67.55 p
39
#include<iostream.h> void main() { int a=200; int &b=a; cout << &a << " a=10; b=20; cout << a << " " << &b <<endl; " << b << endl;
Digitech Technologies 40
output 0x0012FF7C 20 20
0x0012FF7C
void main() { int x=10,y=20; swap(&x,&y); cout << x << " << endl; } Output 20 10
" << y
void main() { int x=10,y=20; swap(x,y); cout << x << " << endl; } Output 20 10
" << y
Digitech Technologies
41
Output 90 300
42
Objects
The real or virtual world is made of objects. The objects exist in some relationship with other objects. A programming language should enable programmers to create objects that behave like real world objects. Software Objects define an abstract representation of real or virtual world entities in order to simulate them. Objects encapsulate a portion of knowledge in a problem domain or the world in which they evolve.
Digitech Technologies
43
Objects
Definitions An atomic entity composed of state, behavior. An Object is a region of storage with associated semantics. An Object is an instance of a data type. An object is a self-contained entity that can maintain its state.
Digitech Technologies
44
Objects
State The state groups the values of all the attributes of an object at a given time, where an attribute is a piece of information. Behavior
The behavior groups all the abilities of an object and describes the actions and reactions of that object. Each individual behavioral component is called an operation. The operations of an object are triggered as a result of an external event, represented in the form of a message sent by another object.
Digitech Technologies
45
a.set_time();
or b->set_time();
Digitech Technologies
46
Abstraction
A class or a structure should hide (protect) its data members and expose its operations to outside world. C++ members can be protected or exposed to others by using access specifier. C++ access specifiers
private: A private member can be accessed only from within the class members. public: A public member can be accessed from any where. protected: A protected member is same as private member to the class but it can be accessed in derived type.
Digitech Technologies 47
// legal
// illegal
49
Objects
An instance of a class in memory In a program, there can be many instances of a class (Many objects of same class) If class can be viewed as a type, then object is a variable of that type
Examples: Trainee is a class. Arun is an Object of Trainee class Educator is a class. Rajagopal is an Object of Educator class
Digitech Technologies
50
Output -858993460
Digitech Technologies 51
Constructor
Constructors are special member functions and have the same name as the class itself. A constructor implicitly gets called when an object of that type is created. Constructors have no return value ( not even void ).
If a class does not have any constructor , then C++ adds default constructor without any statements in it.
Digitech Technologies
52
Constructor
#include<iostream.h> #include<string.h> class student { char name[20]; int age; public: student() { age=18; strcpy(name,"unknown"); } student(char *a,int b) { age=b; strcpy(name,a); } void show() { cout << name << " }; void main() { student s("Ravi Kumar",20); s.show(); }
20
Digitech Technologies
53
Destructor
Like constructors being invoked at the time of creation, a destructor is invoked when an object is destroyed Destructors will have the same name as the class preceded by a tilde(~) No arguments No return value Cannot be overloaded Used for housekeeping job for recovering the memory allocated
class employee { : ~employee() { }
Digitech Technologies 54
Anonymous Object
#include<iostream.h> #include<string.h> int main() { person p1("ramesh"); class person p1.display(); { { char name[20]; person t("Kiran"); public: p1=t; person(){ name[0]=0; } } p1.display(); person(char *a) return 0; int main() } { { strcpy(name,a); person p1("ramesh"); } p1.display(); { void display() p1=person("Kiran"); { } cout << name << endl; p1.display(); } return 0; } void setName(char *a) { strcpy(name,a); } };
Digitech Technologies 56
Digitech Technologies
57
Mutator methods Mutator methods can modify the active object state.
Digitech Technologies
59
Constant members
#include<iostream.h> #include<string.h> int main() { Employee e("Rajesh",1001,8900); e.show(); e.setSal(10000); e.show(); return 0; }
class Employee { const int empid; int sal; char name[20]; public: Employee(char *a,int b,int c) : empid(b) , sal(c) { strcpy(name,a); } void show() const { cout << empid << " " << name << " " << //sal=1000; } void setSal( int a ) { sal=a; } };
Digitech Technologies
Output 1001 Rajesh 8900 1001 Rajesh 10000 sal << endl;
60
Size of the class demo is four bytes but not eight. Size of a class is the sum of the sizes of non-static data members
Static Members
#include<iostream.h> class car { static int count; public: car(){ count++; } ~car(){ count--; } static int getcount() { return count; } }; int main() { car a,b,c,d; cout << car::getcount() <<endl; { car e,f; cout << car::getcount() <<endl; } cout << car::getcount() <<endl; return 0; Output } 4 6 4
Digitech Technologies 64
EmployeeThree
EmployeeTwo
Data members are assigned seperate memory locations for seperate objects
EmployeeOne
Digitech Technologies
65
this pointer
this pointer is a pointer that is automatically available in all non-static member functions of a class. It allows objects to access its own address It points to the current object, the object that invoked the method. When a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object Since static functions are not members of a class instance, this pointer cannot be used with static member functions.
Digitech Technologies
66
this pointer
A class instance have a copy of data members but not member functions. All instances of a class share a single copy of member functions. If this is the case then how a member function know which instance it is supposed to be working on. The answer lies in the fact that the a member function implicitly uses a special pointer this which a hidden parameter to the member function. this pointer points to the object that is used to invoke the member function. Within member function all member references are changed to this->member
Digitech Technologies 67
this pointer
The this pointer can be used to differentiate between instance variables and local variables in (which have same names) a member function. void main() #include<iostream.h> { class demo demo a(67); { int num; a.store(55); public: a.display(); // 55 demo():num(0){} } demo(int a):num(a){} void display() { cout<<num<<endl; } void store(int num) { this->num=num; //demo::num=num; } };
Digitech Technologies 68
this pointer
#include<iostream.h> #include<string.h> void main() { radio a("Hyd"),b("Sec"),c("Mum"),d("Kol"); b.send("Hello"); }
class radio { static int count; static radio *r[50]; output char name[20]; from Hyd:Hello public: from Mum:Hello radio(char *k) from Kol:Hello { strcpy(name,k); r[count]=this; count++; } void receive(char *k){ cout<<"from "<<name<<':'<<k<<endl; } void send(char *k) { for(int i=0;i<count;i++) if( this!=r[i] ) r[i]->receive(k); } }; Write a program to create some radio stations. int radio::count=0; Show a message sent by a station is received by all radio * radio::r[50]; other stations.
Digitech Technologies 69
Digitech Technologies
70
class Date { private: //Data members public: short GetDayOfMonth (); char* GetDateOfWeek (); };
Digitech Technologies 72
File Footer Block : All files should have this footer at the end of the file.
Digitech Technologies
75
};
#endif // _EMPLOYEE_H
/****************************************************** * End of Employee.h *******************************************************/
Digitech Technologies 77
/********************************************************** * GetEmployeeNumber * PARAMETERS: None * RETURNS: int m_iEmpNum **********************************************************/ int Employee::GetEmployeeNumber() { return m_iEmpNum; }
Digitech Technologies 78
Digitech Technologies
80
};
Output 20 30
81
Digitech Technologies
Aggregation
Aggregation refers to a relationship where one class contains objects of another class as its members Aggregation leads to Has-A relationship
Digitech Technologies
82
The general forms of new and delete are shown here: p_var = new type; delete p_var; Here, p_var is a pointer variable that receives a pointer to memory that is large enough to hold an item of type type.
Use malloc/realloc to allocate memory for the simple variables Use new for allocating memory for the objects
Digitech Technologies 83
Suppose the allocated memory is not freed then this space will remain allocated even after the execution of the program. Such memory spaces could be very dangerous and may lead to the system crash due to lack of free memory.
Digitech Technologies
84
Digitech Technologies
85
String class
#include<iostream.h> #include<string.h> class str { char *s; public: str() { s=new char[1]; *s=0; } str(char *a) { s=new char[ strlen(a)+1 ]; strcpy(s,a); } void display() { cout<<s<<endl; } void copy(char *a) { delete s; s=new char[ strlen(a)+1 ]; strcpy(s,a); } void add(char *a) { char *t t=new char[ strlen(s)+strlen(a)+1 ]; strcpy(t,s); strcat(t,a); Output delete s; abc s=t; welcome xyz }
Digitech Technologies
86
Copy constructor
A built-in type variable can be initialized with one that is already existing variable of the same type. This is also extended to user defined types created using structures. In case of user defined types, the initialization is done using member by member copy of the structure data members. In C++ the same is applicable to variables of class types.
The default member by member copy is not sufficient in case of a class with pointer data members. The initialized object pointer member and the existing object pointer member, both point to same memory space. If the memory space is released with one of the object pointer data member, then the other object pointer member is invalid.
Digitech Technologies
87
Copy constructor
A copy constructor is automatically invoked when a new object is initialized with an existing object of the same class type. class_name::class_name( const class_name &var ); The parameter to copy constructor must be a reference of the same type.
The copy constructor of a class is called when 1)An instance of a class created from an existing instance of the same class. 2)A function is called and an argument of class type is passed by value.
If a class does not have copy constructor, then C++ provides a default copy constructor. The default copy constructor simply uses memberwise copying.
Digitech Technologies 88
Copy constructor
#include<iostream.h> #include<string.h> class str { char *s; public: : void abc( str k ) { strcpy(k.s,aaa); } }; void main() { str a,b(Hello); b.display(); a.abc(b); b.display(); } #include<iostream.h> #include<string.h> class str Hello { Hello char *s; public: : void abc( str k ) { strcpy(k.s,aaa); } str( str &m ) { s=new char[ strlen(m.s)+1]; strcpy(s,m.s); } }; void main(){ same as before }
Output
Digitech Technologies
89
Inline Functions
We can create short functions that are not actually called; rather, their code is expanded in line at the point of each invocation. This is process is somewhat similar to using a function-like macro. To make a function inline, prefix the function definition with inline class Rectangle { double Length; double Breadth ; public: inline double CalcArea() { } void Show(){ } // is also inline function void Display(); // while defining, should be decl. inline };
Digitech Technologies 90
Friend Functions
A friend function is a non-member function that is granted permission to access private members. A class may grant friendship to a global function
to another class
to a particular member function of another class
Digitech Technologies
91
Friend Functions
Global friend function #include<iostream.h> class demo { int num; public: demo():num(0){} demo(int a):num(a){} int sum1(demo x) { return num+x.num; } friend int sum2(demo,demo); };
int sum2(demo x,demo y) { return x.num+y.num; } void main() { demo a(5),b(7); cout<<a.sum1(b) <<endl; cout<<sum3(a,b) <<endl;
/* output 12 12 */
Digitech Technologies
92
Friend Class
#include<iostream.h> class demo { int num; public: demo():num(0){} demo(int a):num(a){} friend class abc; };
/* Output
45 45
class abc */ { public: void show() { demo k(45); cout << k.num << endl; } void display() { demo k(45); cout << k.num << endl; } };
Digitech Technologies 93
Friend Functions
#include<iostream.h> class abc { public: void show(); void display(); }; class demo { int num; public: demo():num(0){} demo(int a):num(a){} friend void abc::show(); }; void abc::show() { demo k(45); cout << k.num << endl; } void abc::display() { demo k(45); //cout << k.num << endl; } void main() { abc a; a.show(); a.display(); }
Digitech Technologies 94
Operator overloading
Consider the following messages on a string object. str a; a.copy(Hello); a.add(Abc); str a; a=Hello; a+Abc;
Using = and + is easy to remember and more readable than the function names like copy and add. But C++ operators cannot operate on user defined types. Operator overloading is a process of providing a user defined behavior to an operator on user defined data_type. The overloaded operators behavior remains unchanged on other data types.
Digitech Technologies 95
Operator overloading
Operator overloading rules 1) Only existing operators can be overloaded.
3) The overloaded operators priority and associativity cannot be changed. 4) Operators can be overloaded only on user defined types.
Digitech Technologies
96
Operator overloading
An operator is overloaded by providing a special function called operator.
When the compiler see an operator on user defined type, it will search and map the statement to the special function operator provided for the operator and the operand types. Syntax: data_type operator opr_char( [ data_type p1 ] [, data_type p2 ] ) { }
Digitech Technologies
97
Operator overloading
Operators can be overloaded as member functions and also as global functions.
To be a member function, the first operand in the expression must be of the class type.
The first operand is used as active object to call the method. The other operand if exists will become formal parameter to the method. A global operator overloading is most likely made a friend function to a class. This is in order to gain access on private members of the class.
Digitech Technologies 98
Operator overloading
#include<iostream.h> #include<string.h> class str { char *s; public: str() { s=new char(0); } str(char *a) { s=new char[ strlen(a)+1 ]; strcpy(s,a); } void display() { cout<<s<<endl; } char* operator=(char *a)
delete s;
s=new char[ strlen(a)+1 ]; return a; strcpy(s,a);
} char* operator+(char *a) { char *t=new char[ strlen(s)+strlen(a)+1 ]; strcpy(t,s); strcat(t,a); return t; } friend char* operator+(char*,str);
};
Digitech Technologies
99
Operator overloading
char* operator+(char *a, str x) { char *t=new char[ strlen(a)+strlen(x.s)+1 ]; strcpy(t,a); strcat(t,x.s); return t; } void main() {
str a,b(hello),c,d,e;
e=a=abc; c=b+xyz; d=123+b; a.display(); b.display(); c.display(); d.display(); e.display();
Digitech Technologies
100
Ellipsis ()
Ellipsis enables a function have variable number of arguments ( like with printf and scanf functions ). data_type function_name( ) { } Ellipsis can be accessed using va_list, va_start and va_arg defined in stdarg.h header file. First create a variable of va_list type va_list k; After creating the list variable, the list need initalized using va_start( va_list , the last known parameter name ) To extract elements from ellipsis use data_type va_arg( va_list , data_type ) Each call to va_arg returns the next element from ellipsis.
Digitech Technologies 101
Ellipsis ()
#include<iostream.h> #include<stdarg.h> void abc(int m,...) { va_list k; va_start(k,m); cout<<endl; for(int i=0;i<m;i++) cout << va_arg(k,int) << " "; } Output void main() 44 55 66 { 67 44 abc(3,44,55,66); abc(2,67,44); 23 77 55 48 34 abc(0); abc(5,23,77,55,48,34); }
Digitech Technologies 102
Operator overloading
#include<iostream.h> #include<stdarg.h> #include<stdlib.h> class array {
int *n,max; a[3]=600; public: for(int i=0;i<10;i++) cout << a[i] << ; array(int a,...) : max(a) } { va_list x; va_start(x,a); n=new int[max]; for(int i=0;i<max;i++) n[i]=va_arg(x,int); } int& operator[](int a) { if(a<0 || a>=max ) { cout<<error in index<<endl; exit(1); } return n[a]; }
};
Digitech Technologies 103
Operator overloading
Simulation of **, the power operator #include<iostream.h> void main() { Number a(5),b(3); cout<<a*b<<endl<<a**b<<endl; }
class Number { int num; public: /* Number():num(0){} Output Number(int a):num(a){} 15 int operator*(Number &a) 125 { */ return num*a.num; } Number* operator*() { return this; } int operator*(Number *a) { int i,n=1; for(i=0;i<a->num;i++) n = n * num ; return n; } };
Digitech Technologies
104
Type Conversions
Example for Built-in type to User-defined type conversion #include<iostream.h> #include<string.h> class demo { int num; public: demo():num(0){} demo(int a):num(a){} demo(char *k) { num = strlen(k); } void display() { cout<<num<<endl; } }; Output void main() 90 { demo a,b(23),c=b,d=45; 23 a=90; 23 a.display(); b.display(); c.display(); d.display(); 45 a=Hello; 5 a.display(); }
Digitech Technologies
105
Type Conversions
Example for User-defined to Built-in type conversion #include<iostream.h> class demo { int n1,n2; public: demo(int a,int b):n1(a),n2(b){} operator int() { return n1+n2; } }; void main() { demo d(45,55); int k; k=d; cout << k << endl; }
// 100
Digitech Technologies 106
Operator overloading
Example for User-defined to User-defined conversion #include<iostream.h> fahrenheit::operator celsius() class celsius; { class fahrenheit return (f-32.0)*5.0/9.0; { } float f; public: void main() fahrenheit():f(0){} { fahrenheit(float a):f(a){} celsius a,b(30); void display(){ cout<<f<<endl; } fahrenheit c,d(100); operator celsius(); }; a=(celsius)d; c=(fahrenheit)b; class celsius { a.display(); float c; b.display(); public: c.display(); celsius():c(0){} d.display(); celsius(float a):c(a){} } void display(){ cout<<c<<endl; } operator fahrenheit() { return c*9.0/5.0 + 32.0; } };
Digitech Technologies 107
Inheritance
The process of deriving a new class from an existing class is called Inheritance The old class is referred to as the base class and the new class is called the derived class or subclass. Through Inheritance, C++ strongly supports the idea of Reusability. That is making use of the existing features to create the new feature. All the objects in this world come under some kind of classification. Inheritance allows the creation of hierarchical classification. For example, the bike Yamaha is a part of the class Two Wheeler which is again a part of the class Vehicle.
Digitech Technologies
108
Inheritance
Digitech Technologies
109
Inheritance
Generalization and Specialization Generalization and Specialization are associated with the concept of Inheritance The Trainee class derives the Employee class Employee class is a generalization of Trainee class Trainee class is a specialization of the Employee class
Digitech Technologies
110
Inheritance
Inheritance Relationship is a relation exists between the derived class and base class. Trainee is an Employee
Employee
Trainee
Digitech Technologies
111
Inheritance
Creating derived classes The general format of deriving the properties from one class to another class is : class derived-class-name : [visibility-mode] base-classname [,] { // members of derived class }; Here, the visibility mode is optional and , if present, may be either private , public or protected.
Inheritance
Types of Inheritance based on structure
Digitech Technologies
113
Inheritance
Derivation types Derivation type determines the base members accesibility in the derived class
Derivation type Private Base member private public protected class Access in derived class (inaccessible) private private
Public
Protected
Digitech Technologies
Inheritance
Protected Members The private members cannot be accessed outside the scope of the class. The derived class also cannot access the private members. Sometimes, we want the derived class to access the private members of the base class but at the same time, we dont want to access those members thru the object of the class. Those members come under protected access specifier.
In other words, protected members are private to all, but public to its derived classes.
Digitech Technologies
115
Inheritance
Protected Members Advantages: Derived classes can modify values directly Slight increase in performance; Avoids set/get function call overhead
Disadvantages:
No validity checking - Derived class can assign illegal value Implementation dependent - Derived class member functions more likely dependent on base class implementation - Base class implementation changes may result in derived class modifications resulting in Fragile (brittle) software
Digitech Technologies 116
Inheritance
Constructors in the Base and Derived Classes An instance of a derived class contains the data members inherited from its base class and its own data members. To initialize the members, compiler first calls the base class constructor to initialize base class members, and then calls derived class constructor to initialize the derived class members. The derived class constructor must tell the Compiler which base class constructor to use for base class member initialization. This is provided by using base class parameter list: derive_class( a1,a2,a3, ) : base_class( p1,p2, ) , mem_init { } If base class parameter list is not provided, then compiler automatically calls the base class default constructor.
Digitech Technologies 117
Inheritance
#include<iostream.h> class base { int num; public: base():num(0){} base(int k):num(k){} void show() { cout<<num<<endl; }; void main() { derive d(45); d.show(); d.display();
class derive : public base { int num; public: derive():num(0){} derive(int k):base(k/2),num(k){} void display() { cout<<num<<endl; } };
Digitech Technologies
/* output 22 45 */
118
Inheritance
Method Overriding Providing different implementation in the derived class for the methods defined in the Base class is called as Method Overriding. The method signatures must be same. In such cases where the derived class objects invoke the overridden methods, the derived class overridden methods are invoked.
Digitech Technologies
119
Inheritance
#include<iostream.h> class base { int num; public: base():num(0){} base(int k):num(k){} void show() { cout<<num<<endl; }; void main() { derive d(45); d.base::show(); d.show();
class derive : public base { int num; public: derive():num(0){} derive(int k):base(k/2),num(k){} void show() { cout<<num<<endl; } };
Digitech Technologies
/* output 22 45 */
120
Inheritance
Point2D and Point3D ( without inheritance ) #include<iostream.h> class twoD { int x,y; public: twoD():x(0),y(0){} twoD(int a,int b):x(a),y(b){} void display() { cout << x << " " << y << " "; } void setx(int a){ x=a; } void sety(int a){ y=a; } }; void main() { threeD td(56,34,90); td.display(); cout<<endl; td.setx(51); td.display(); } class threeD { twoD td; int z; public: threeD():z(0){} threeD(int a,int b,int c):z(c) { td.setx(a); td.sety(b); } void display() { td.display(); cout << z << " "; } void setx(int a){ td.setx(a); } void sety(int a){ td.sety(a); } void setz(int a){ z=a; } };
Digitech Technologies
121
Inheritance
Point2D and Point3D ( with inheritance ) #include<iostream.h> class twoD { int x,y; public: twoD():x(0),y(0){} twoD(int a,int b):x(a),y(b){} void display() { cout << x << " " << y << " "; } void setx(int a){ x=a; } void sety(int a){ y=a; } }; void main() { threeD td(56,34,90); td.display(); cout<<endl; td.setx(51); td.display(); } class threeD : public twoD { int z; public: threeD():z(0) { } threeD(int a,int b,int c): twoD(a,b),z(c){} void display() { twoD::display(); cout << z << " "; } void setz(int a){ z=a; }
};
Digitech Technologies
122
Inheritance
Assignment Operator overloading for a Derived Class Like Copy Constructor of derived class that explicitly calls Copy Constructor of base class, assignment operator overloading of derived class must explicitly call base class assignment operator function. derive derive::operator=(int a) { base::operator=(a); // calling base assignment operator overloading : : }
Digitech Technologies
123
Inheritance
Copy Constructors of Base and Derived Classes When a new instance of derived class created using derive class copy constructor, the Compiler does not automatically call the base class copy constructor. Instead of the base class copy constructor, the compiler calls default constructor of the base class. This problem can be overcome by an explicit call to base class copy constructor from derive class copy constructor.
Digitech Technologies
124
Inheritance
#include<iostream.h> class base { public: base() { cout<<"from base default\n"; } base(base &a) { cout<<"from base copy const\n"; } ~base() { cout<<from base destructor\n; } }; class derive : public base { public: derive(){ cout<<"from derive default\n"; } derive(derive &a) : base(a) { cout<<"from derive copy ~derive(){ cout<<from derive destructor\n; } }; void main() { derive a; derive b=a; }
Digitech Technologies
Output: from base default from derive default from base copy const from derive copy const from derive destructor from base destructor from derive destructor from base destructor
const\n"; }
125
Inheritance
Multiple Inheritance C++ allows a class derived from more than one base or parent classes. The derived class will have all the members of the base classes. The base classes may have members with same name. Use base class name and scope resolution operator ( :: ) to avoid ambigious member reference.
Virtual Inheritance
Suppose a class DERIVE is derived from two different base classes BASE1 and BASE2, which in turn are derived from the same base class COMMON_BASE. It is clear that the DERIVE class will have two copies of COMMON_BASE class members. Virtual inheritance can solve the above problem. When a class derives several times from the same virtual base class, this derive class will have only one copy of the base class.
Digitech Technologies 126
Inheritance
#include<iostream.h> class common_base { int x; public: common_base():x(0){} common_base(int a):x(a){} void show() { cout<<x<<endl; } }; class base1 : virtual public common_base { int x; public: base1():x(0){} base1(int a):x(a){} void show() { cout<<x<<endl; } };
virtual inheritance
Digitech Technologies
127
Inheritance
class base2 : virtual public common_base { int x; public: base2():x(0){} base2(int a):x(a){} void show() { cout<<x<<endl; } }; class derive : public base1,public base2 { int x; public: derive():x(0){} derive(int a):common_base(a), base1(a),base2(a),x(a){} void show() { cout<<x<<endl; } };
virtual inheritance
Digitech Technologies
Inheritance - Example
#include<iostream.h> #include<string.h> class employee { char name[20]; char grade; public: employee(){} employee(char *a,char b):grade(b) { strcpy(name,a); } void display() { cout<<name<< } char getgrade(){ return grade; }
Digitech Technologies 129
<<grade<< ;
};
Inheritance - Example
class manager : public employee { int sal;
public:
manager(){} manager(char *a,int b):employee(a,A),sal(b){} void display() { employee::display(); } int pay() { return sal; } cout<<sal<< ;
};
Digitech Technologies
130
Inheritance - Example
class wage_employee : public employee { int hours,rate;
public:
wage_employee(){} wage_employee(char *a,int b,int c):employee(a,C), hours(b),rate(c){} void display() { employee::display(); cout<<hours<< <<rate<< ; } int pay(){ return hours*rate; } protected: wage_employee(char *a,int b,int c,char d):employee(a,d), hours(b),rate(c){}
};
Digitech Technologies
131
Inheritance - Example
class sales_person : public wage_employee { int comm,sales; public: sales_person(){} sales_person(char *a,int b,int c,int d,int e):wage_employee(a,b,c,B), comm(d),sales(e){} void display() { wage_employee::display(); } cout<<comm<< <<sales<< ;
};
Digitech Technologies
132
Inheritance - Example
void main() { manager m[50]; wage_employee w[50]; sales_person s[50]; char ch,name[20]; int mmax,smax,wmax,sal,hours,rate,comm,sales; mmax=wmax=smax=0; while( ch!='q' ) { cout<<"\nwage employee cin>>ch; cin.get();
sales person
manager
quit ";
Inheritance - Example
if(ch=='m') { cout<<"Enter salary "; cin>>sal; cin.get(); } if(ch=='w' || ch=='s') { cout<<"Enter hours "; cin>>hours; cout<<"Enter rate "; cin>>rate; cin.get(); m[mmax]=manager(name,sal); mmax++;
Inheritance - Example
if(ch=='s') { cout<<"Enter comm "; cin>>comm; cout<<"Enter sales "; cin>>sales; cin.get(); s[smax]=sales_person(name,hours,rate,comm,sales); smax++;
Digitech Technologies
135
Inheritance - Example
int i; long msum=0; for(i=0;i<mmax;i++) { m[i].display(); cout<<m[i].pay()<<endl; msum=msum+m[i].pay(); } long ssum=0; for(i=0;i<smax;i++) { s[i].display(); cout<<s[i].pay()<<endl; ssum=ssum+s[i].pay(); } long wsum=0; for(i=0;i<wmax;i++) { w[i].display(); cout<<w[i].pay()<<endl; wsum=wsum+w[i].pay(); } cout<<msum+ssum+wsum <<endl;
} /* end of main */
The for loops are identical except the object references This is because the data is stored in three different arrays
136
Digitech Technologies
Inheritance - Example
void main() { employee *e[150];
sales person
manager
quit ";
Inheritance - Example
if(ch=='m') { cout<<"Enter salary "; cin>>sal; cin.get(); e[max]=new manager(name,sal); max++;
} if(ch=='w' || ch=='s') { cout<<"Enter hours "; cin>>hours; cout<<"Enter rate "; cin>>rate; cin.get(); if(ch=='w') { e[max]=new wage_employee(name,hours,rate); max++; }
Digitech Technologies 138
Inheritance - Example
if(ch=='s') { cout<<"Enter comm "; cin>>comm; cout<<"Enter sales "; cin>>sales; cin.get(); e[max]= new sales_person(name,hours,rate,comm,sales); max++;
Digitech Technologies
139
Inheritance - Example
int i; for(i=0;i<max;i++) { switch( e[i]->getgrade() ) { case 'A': ((manager*)e[i])->display(); cout<<endl; break; case 'B': ((sales_person*)e[i])->display(); cout<<endl; break; case 'C': ((wage_employee*)e[i])->display(); cout<<endl; break; } } The code repetition problem still exists
Digitech Technologies
140
Polymorphism
Is a Greek word, which means one name, multiple forms. Is the ability of objects to respond differently to the same message. The kind of response is dependent on the data types used in a given instance. Allows objects having different internal structure to share the same external interface.
Digitech Technologies
141
Polymorphism
Polymorphism - Binding Binding refers to the process of linking a procedure call to the code to be executed in response of the call. Are of two types. Static binding or Early binding and Dynamic binding or Late binding. In Static binding the code associated with a given procedure call is resolved during compiler time. In Dynamic binding the code associated with a given procedure call is resolved during run-time.
Digitech Technologies
142
Polymorphism
#include<iostream.h> #include<string.h> class class class class employee ... manager : public employee wage_employee : public employee ... sales_person : public wage_employee ...
void main() { employee *e=new sales_person("Ravi Kumar",5,90,500,102); e->display(); cout<<endl; ((sales_person*)e)->display(); cout<<endl; output Ravi Kumar Ravi Kumar
Digitech Technologies
B B 5
90
500
102
143
Polymorphism
#include<iostream.h> #include<string.h> class class class class employee { virtual void display(){ } ... manager : public employee wage_employee : public employee ... sales_person : public wage_employee ...
void main() { employee *e=new sales_person("Ravi Kumar",5,90,500,102); e->display(); cout<<endl; ((sales_person*)e)->display(); cout<<endl; output Ravi Kumar Ravi Kumar
Digitech Technologies
B 5 B 5
90 90
500 500
102 102
144
Polymorphism
Virtual functionsDynamic Polymorphism Instead of making type casting the pointer the same effect can be got by defining the overridden methods as virtual in the base class class employee { virtual void display(); The base class pointers can now be pointing to derived types employee *e=new sales_person(); e->display(); This actually invokes the sales_person class method This determination of which version of the overridden method to invoke happens at run time. This is known as Dynamic Binding
Digitech Technologies 145
Polymorphism
class employee { : public: employee(){} employee(){} virtual void display(){ } }; : Compiler Error: : 'pay' : is not a member of 'employee' void main() { employee *e=new sales_person("Ravi Kumar",5,90,500,102);
e->display(); cout<<e->pay()<<endl;
Digitech Technologies
146
Polymorphism
class employee { : public: employee(){} employee(){} virtual void display(){ } virtual int pay(){ return 0; } }; Output : Ravi Kumar B 5 90 500 102 950 : void main() { employee *e=new sales_person("Ravi Kumar",5,90,500,102); e->display(); cout<<e->pay()<<endl;
Digitech Technologies 147
Polymorphism
class employee { : virtual void display(){ } manager pay virtual int pay(){ return 0; } }; class manager : public employee { : public: Output // int pay(){ return sal; } Ravi Kumar A 19000 0 }; : void main() { employee *e=new manager("Ravi Kumar",19000); e->display(); cout<<e->pay()<<endl; }
Digitech Technologies 148
Polymorphism
Abstract class At times we may not want the objects of the base class to be created at all If one of the methods of the base class is made pure virtual function then that class will become abstract. Example: virtual int pay()=0; No objects of abstract class can be created. But pointers to abstract class can be created Abstract classes act like an interface.
Digitech Technologies 149
Polymorphism
class employee { : virtual void display(){ } virtual int pay()=0; }; class manager : public employee { : public: Compiler Error: // int pay(){ return sal; } 'manager' : cannot instantiate abstract class }; : void main() { employee *e=new manager("Ravi Kumar",19000); e->display(); cout<<e->pay()<<endl; }
Digitech Technologies 150
Polymorphism
class employee { : virtual void display(){ } virtual int pay()=0; }; class manager : public employee { : public: Output: int pay(){ return sal; } Ravi Kumar A 19000 19000 }; : void main() { employee *e=new manager("Ravi Kumar",19000); e->display(); cout<<e->pay()<<endl; }
Digitech Technologies 151
Polymorphism
#include<iostream.h> class shape { public: virtual int area()=0; }; class circle : public shape { int r; public: circle(int a):r(a){} int area() { return 22.0/7.0*r*r; } }; class square : public shape { int s; public: square(int a):s(a){} int area() { return s*s; } };
Digitech Technologies
Shape Example
152
Polymorphism
class rectangle : public shape Shape Example { int h,w; public: rectangle(int a,int b):h(a),w(b){} int area() { return h*w; } }; void main() { shape *s[]={ new circle(5), new rectangle(6,10), new rectangle(12,4), new square(5), new circle(15), new circle(6), new circle(19), new square(16), new square(25) }; long sum=0; int max = sizeof(s) / sizeof(s[0]) ; for(int i=0;i<max; i++) sum=sum+s[i]->area(); cout << sum <<endl; }
Digitech Technologies 153
Polymorphism
General purpose sort Example #include<iostream.h> #include<string.h> class sort { public: class sortable static void bubble(sortable **e,int max) { { public: sortable *t; virtual int compare(sortable*)=0; int i,k; }; for(i=0;i<max-1;i++) for(k=0;k<max-i-1;k++) if( e[k]->compare(e[k+1]) >0 ) { t=e[k]; Any user-defined types can e[k]=e[k+1]; be sorted using the sort e[k+1]=t; } class, provided the class } defines compare method. };
Digitech Technologies 154
Polymorphism
class employee : public sortable General purpose sort Example { char name[20]; int sal; public: employee(){} employee(char *a,int b):sal(b) { strcpy(name,a); } void show() { cout<<name<<" --- "<<sal<<endl; } int compare(sortable *k) { employee *e=(employee *)k; return sal-e->sal; } };
Digitech Technologies
155
Polymorphism
#define MAX 5 void main() { employee *e[MAX]={ General purpose sort Example
};
Output Sham --- 8000 Ravi --- 9000 Sing --- 10000 Neha --- 11000 Giri --- 12000
Digitech Technologies 156
Polymorphism
#include<iostream.h> Virtual Destructor
class base { public: ~base(){ cout<<"from base destructor\n"; } }; class derive : public base { public: ~derive(){ cout<<"from derive destructor\n"; } }; void main() { base *d=new derive(); delete d; } Output from base destructor
Digitech Technologies
157
Polymorphism
#include<iostream.h> Virtual Destructor
class base { public: virtual ~base(){ cout<<"from base destructor\n"; } }; class derive : public base { public: ~derive(){ cout<<"from derive destructor\n"; } }; void main() { base *d=new derive(); delete d; } Output from derive destructor from base destructor
Digitech Technologies
158
Exception Handling
An Exceptional condition is an event that occurs during the execution of C++ program (runtime anomalies) causing a program to interrupt.
Examples: Out-of-bound array subscript, arithmetic overflow or underflow, division by zero, out of memory, invalid function parameter, etc.,
An exceptional condition may be either an unexpected error or an expected error at an unpredictable time.
Digitech Technologies
159
Exception Handling
The process of detecting and taking an appropriate action for exceptions is referred to exception handling. Exception handling involves the following steps. (1) Find the error (try), (2) Inform that an error as occurred (throw), (3) Receive the error information (catch) & (4) Take corrective actions (Handle) The C++ exception handling mechanism is built upon three keywords namely try, throw and catch.
Digitech Technologies
160
Exception Handling
The keyword try is used to preface a block of statements which may generate exceptions. This block of statements is known as try block.
The throw statement is used to inform that an exception has occurred. It is coded within the try block.
The keyword catch is used to preface a block called catch block to receive and handle the exception informed by the throw statement. The catch block must immediately follow the try block that throws the exception.
Digitech Technologies
161
Exception Handling
Syntax for try and catch blocks
: try {
Digitech Technologies
162
Exception Handling
When the try block throws an exception, the program control leaves the try block and enters the catch block. If the type of the object thrown matches the argument type in the catch statement, then the catch block is executed otherwise the program is aborted with the help of the abort ( ) function. If no exception is thrown, the control goes to the statement immediately following the catch block.
Digitech Technologies
163
Exception Handling
#include<iostream.h> int abc(int x,int y) { if(y==0) throw "/ by 0 error"; return x/y; } void main() { int a,b,c; cout<<"Enter two numbers "; cin>>a>>b; try { c=abc(a,b); cout<<c<<endl; } catch(char *e) { cout<<e<<endl; } }
Digitech Technologies 164
Simple example
Exception Handling
#include<iostream.h> int abc(int x,int y) { if(y==0) throw "/ by 0 error"; return x/y; } void main() { int a,b,c; char ch; try {
Raising exception from within try block and from outside try block
Exception Handling
c=abc(a,b); cout<<c<<endl;
Raising exception from within try block and from outside try block
Digitech Technologies
166
Exception Handling
It is possible to have multiple catch blocks following a try block to handle all possible exceptions. In some situations, we may not be able to anticipate all possible types of exceptions. In such cases we can catch all exceptions using the following form of catch statement. Syntax to catch all types of exceptions
Digitech Technologies
167
Templates
Is mechanism provided to implement the concept of generic programming. Allows programmers to create a family of similar classes or functions. Eliminate code duplication for different types and thus make the software development easier and more manageable. Are to be defined with parameters that would be replaced by a specified data type at the time of actual use of the class or function.
Digitech Technologies
168
Templates
Templates are example code for compiler, which generates actual code with the help of the template. Templates are of two types Function templates: Function templates are also known as parameterized or generic functions. Class templates: Class templates are also known as parameterized or generic types. Function Template syntax: template< class T [ , class M , ..... ] > data_type function_name( data_type var1, ... ) { data_type v1,v2; // local variables }
Digitech Technologies 169
Templates
#include<iostream.h> #include<string.h> template< class T > T max( T x, T y ) { return x>y ? x : y; } char* max( char *x, char *y ) { if( strlen(x)>strlen(y) ) return x; }
else return y;
void main() { int a=10,b=20; char c=x,d=h; float e=56.99,f=88.34; char s1[20]=welcome,s2[20]=hello; cout << max(a,b) << endl << max(c,d) << endl << max(e,f) << endl << max(s1,s2) << endl; }
Digitech Technologies 170
Templates
#include<iostream.h> template<class T> class demo { T data; public: demo(){} demo(T a):data(a){} void display() { cout << data << endl; }
};
void main() { demo<int> a(67); demo<char*> b(hello); demo<float> c; } a.display(); b.display(); c.display();
Digitech Technologies
171
Templates
General Purpose Sorting Template Function
#include<iostream.h> #include<string.h> template<class T> void bubble(T **e,int max) { T *t; int i,k; for(i=0;i<max-1;i++) for(k=0;k<max-i-1;k++) if( e[k]->compare(e[k+1]) > 0 ) { t=e[k]; e[k]=e[k+1]; e[k+1]=t; }
Digitech Technologies
172
Templates
General Purpose Sorting Template Function
class employee { char name[20]; int sal; public: employee(){} employee(char *a,int b):sal(b) { strcpy(name,a); } void show() { cout<<name<<" --- "<<sal<<endl; } int compare(employee *k) { return sal-k->sal; } };
Digitech Technologies 173
Templates
General Purpose Sorting Template Function
#define MAX 5 void main() { employee *e[MAX]={
new employee("Ravi",9000), new employee("Giri",12000), new employee("Sham",8000), new employee("Sing",10000), new employee("Neha",11000)
};
Output Sham --- 8000 Ravi --- 9000 Sing --- 10000 Neha --- 11000 Giri --- 12000
174
Digitech Technologies
Templates
Class Template : Array Example
#include<iostream.h> #include<stdarg.h> #include<stdlib.h> template<class T,int s> class array { T *n; int max; public: array(int a,...) : max(a) { va_list x; va_start(x,a); n=new T[max]; for(int i=0;i<max;i++) n[i]=va_arg(x,T);
Digitech Technologies
175
Templates
Class Template : Array Example
T& operator[](int a) { a=a-s; if(a<0 || a>=max ) { cout<<"error in index"<<endl; exit(1); } return n[a]; } Output 56 7 89 45 33 8 9 32 11 30 Hello Welcome
};
void main() { array<int,0> a(10,56,7,89,45,33,8,9,32,11,30); array<char*,2> b(2,"Hello","Welcome"); int I; a[3]=600; for(i=0;i<10;i++) cout << a[i] << " "; cout<<endl; for(i=2;i<4;i++) cout << b[i] << " "; }
Digitech Technologies
176
Templates
#include<iostream.h> template<class T> class demo { T data; public: demo(){} demo(T k):data(k){} void show(); }; template<class T> void demo<T>::show() { cout<<data<<endl; } template<class T> class derive : public demo<T> { };
Digitech Technologies 177
void main() { demo<int> a(45); demo<char*> b("Hello"); demo<float> c; a.show(); b.show(); c.show();
IO Streams
Streams are channels of communication between programs and source/destination of data A stream is either a source of bytes or a destination for bytes. Provide a good abstraction between the source and destination Abstract away the details of the communication path from I/O operation Streams hide the details of what happens to the data inside the actual I/O devices. Streams can read/write data from/to blocks of memory, files etc...
Digitech Technologies
178
IO Streams
Reads
Source Stream Program
Digitech Technologies
179
IO Streams
The stream classes are defined in iostream.h and fstream.h header files. The stream classes are of two types. Console streams and File streams. ios
istream
ostream
ofstream
180
IO Streams
A stream property can be set by using formatting flags. Formatting flags are enums defined in ios class. The formatting flags are
output number format is decimal output number format is octal output number format is hexadecimal hexadecimal alphabets ( a-f ) in uppercase
left adjust data in a field width right adjust data in a field width + prefixed to a positive value prefix the base indicator no_prefix --- decimal ex: 65 0 prefix --- octal ex: 065 0x prefix --- hexadecimal ex: 0x65
Digitech Technologies 181
IO Streams
Methods for setting/resetting formatting flags setf(long flag) sets specified flag without affected other flags unsetf(long flag) resets specified flag without affected other flags #include<stdio.h> #include<iostream.h> void main() { printf("%x %d\n",65,70); cout.setf(ios::hex); cout<<65<<" "; cout.unsetf(ios::hex); cout.setf(ios::dec); cout<<70<<endl;
Digitech Technologies
Output 41 70 41 70
182
IO Streams
Method for setting field width width(int) :the width set is valid only for the next argument printed.
#include<stdio.h> #include<iostream.h> void main() { printf("*%-4d*\n*%10d*\n",65,70);
Output
IO Streams
Method for setting padding character : fill(char) padding character is a character used to fill unused spaces in a #include<iostream.h> void main() { cout.width(4); cout.setf(ios::left); cout.fill('*'); cout<<65<<endl; cout.width(10); cout.setf(ios::right); cout.unsetf(ios::left); cout.fill('-'); cout<<70<<endl;
Digitech Technologies
184
IO Streams
Unformatted input methods char get() get() is same as getchar function in C get(char *dest, int max, char termination =\n) gets input from buffer and stores at dest. The characters input is either max or upto the termination character. getline(char *dest, int max, char=\n) getline() is same as get(...) except it extracts data from buffer including the termination character. read(char *dest, int max) read() gets max characters from input buffer. It does not have any termination character.
Digitech Technologies 185
IO Streams
#include<iostream.h> void main() { char s[80]; cout<<"Enter name : "; cin>>s; } cout<<s<<endl; } #include<iostream.h> void main() { char s[80]; cout<<"Enter name : "; cin.get(s,80); cout<<s<<endl;
Digitech Technologies
186
IO Streams
#include<iostream.h> void main() { char s1[80],s2[80]; cout<<"Enter name : "; //cin.get(s1,80); //cin.get(); cin.getline(s1,80); cout<<"Enter name : "; cin.get(s2,80); } cout<<s1<<endl<<s2<<endl;
Output Enter name : ravi Enter name : giri ravi giri
Digitech Technologies
187
IO Streams
Read method is used to read a random access file #include<iostream.h>
Digitech Technologies
188
IO Streams
Formatted input methods The formatted input methods are >> operator overloading providedin istream class. istream& operator>>(int&); istream& operator>>(unsigned int&); istream& operator>>(char&); istream& operator>>(unsigned char&); istream& operator>>(char*); istream& operator>>(float&); : Formatted output methods The formatted output methods are the << operator overloading provided in ostream class. ostream& ostream& ostream& ostream& ostream& ostream& operator<<(int); operator<<(unsigned int); operator<<(char); operator<<(unsigned char); operator<<(char*); operator<<(float); :
Digitech Technologies 189
IO Streams
Customizating cin and cout objects #include<iostream.h>
class employee { char name[20]; int sal; friend istream& operator>>(istream &,employee &); friend ostream& operator<<(ostream &,employee &); };
istream& operator>>(istream &k,employee &m) { cout<<"Enter name : "; cin.getline(m.name,20); cout<<"Enter sal : "; cin>>m.sal; return k; }
Digitech Technologies
190
IO Streams
Customizating cin and cout objects ostream& operator<<(ostream &k,employee &m) { cout<<m.name<<" --- "<<m.sal<<endl; return k; } void main() { employee e; cin>>e; cout<<e; Output Enter name : Ravi Kumar Enter sal : 9000 Ravi Kumar --- 9000
Digitech Technologies
191
IO Streams
cin customization #include<iostream.h> istream& operator>>(istream &a,void *b) { cout<<(char*)b; return a; } void main() { int a,b;
cin >> (void*)Enter a number >> a >>(void*)ENTER A NUMBER >> b; cout << a+b << endl;
}
Digitech Technologies 192
IO Streams
File Streams Sequential access file : In sequential file records can only be read sequentially. To read records randomly, the address of Nth record should known. Sequential file record size varies, that is why the address of Nth record can not be found. Random access file : In random access files records can be read randomly. Random records size is fixed, that is why address of Nth record can be found. ( rec_number - 1 ) * ( size of record )
Digitech Technologies 193
IO Streams
File stream classes are defined in fstream.h header file.
Ifstream ifstream() ifstream(char *fname,int mode=ios::in) open(char *fname,int mode=ios::in) close(); long tellg() seekg(long position,int seek_direction=ios::beg) ad ) ofstream ofstream() ofstream(char *fname,int mode=ios::out) open(char *fname,int mode=ios::out) close(); long tellp() seekp(long position,int seek_direction=ios::beg) fstream fstream() fstream(char *fname,int mode) open(char *fname,int mode) ...
Digitech Technologies 194
IO Streams
File Open Modes ios::in file opened to input ios::out file opened to output ios::app file opened to append records File Seek Direction ios::beg set file pointer from beginning of the file ios::cur set file pointer from current position of the file ios::end set file pointer from end of the file File Status Methods int good() returns true value if the last operations successful int bad() returns true value if last operation failed int eof() returns true value if end of file is reached
Digitech Technologies
195
IO Streams
Appends a record to emps.dat sequential file #include<fstream.h> void main() { char name[20]; int sal; cout << Enter emp name ; cin.getline(name,20); cout << Enter salary ; cin >> sal; ofstream x(emp.dat,ios::app); if( x.bad() ) { cout << error\n; x << name << , << sal << endl; }
Digitech Technologies 196
return 1;
IO Streams
Reads records from emps.dat and prints them on screen #include<fstream.h> void main() { char name[20]; int sal; ifstream x(emp.dat); if( x.bad() ) { cout << error\n; return 1; } while( !x.eof() ) { x.getline(name,20,,); x >> sal; if( x.good() ) cout << name << ----- << sal; } x.close(); }
Digitech Technologies 197
IO Streams
Appends a record to empr.dat random file #include<fstream.h> struct record { char name[23]; int sal; }; void main() { record r; cout << Enter emp name ; cin.getline(r.name,23); cout << Enter salary ; cin >> r.sal; ofstream x(empr.dat,ios::app); if( x.bad() ) { cout << error\n; return 1; } x.write( (char*)&r,sizeof( r )); }
Digitech Technologies 198
IO Streams
Reads records randomly #include<fstream.h> struct record { char name[23]; int sal; };
void main() { record r; int rec,max; ifstream x(empr.dat); if( x.bad() ) { cout << error\n; x.seekg(0,ios::end); max=x.tellg()/sizeof( r );
return 1; }
Digitech Technologies
199
IO Streams
rec=1; while( rec>0 ) { cout << enter a record number 1 to << max << : ; cin >> rec; cin.get(); if(rec>=1 && rec<=max) { x.seekg( (rec-1)*sizeof( r ),ios::beg ); x.read( (char*)&r,sizeof( r ) ); cout << r.name << ---- << r.sal << endl; } else cout << invalid record number\n; } x.close(); }
Digitech Technologies 200
IO Streams
Manipulators Manipulators are objects that can be used within the chain of insertion and extraction operators. Manipulators are used to set stream attributes from within the chain of << or >> operators. Manipulators are of two types Built-in manipulators without arguments dec - sets output format to decimal oct - sets output format to octal hex - sets output format to hexadecimal endl - generates newline sequence
Output #include<iostream.h> 41 void main() 70 { cout << hex << 65 << endl << dec << 70 << endl; }
Digitech Technologies 201
IO Streams
Built-in manipulators with single argument Method Manipulator -------------------------------------------setf(long) setiosflags(long) unsetf(long) resetiosflags(long) width(int) setw(int) fill(char) setfill(char) --------------------------------------------The single argument manipulators are defined in iomanip.h header file.
Digitech Technologies
202
IO Streams
#include<iostream.h> #include<iomanip.h> void main() { cout << setw(10) << setiosflags(ios::left) << setfill('*') << 65 << endl << setw(20) << resetiosflags( ios::left ) << setiosflags(ios::right) << setfill('-') << 65 << endl; }
IO Streams
User-Defined Manipulator #include<iostream.h> class set { public: int w,j; char f; set(int a,int b,char c):w(a),j(b),f(c){} }; ostream& operator<<( ostream &a,set b ) { a.width( b.w ); a.fill( b.f ); if( b.j ) {
Digitech Technologies 204
IO Streams
a.setf(ios::right); a.unsetf(ios::left);
void main() { cout << set(10,0,'*') << 65 << endl << set(20,1,'-') << 65 << endl; }
Digitech Technologies
Smart Pointers
Take care of automatic initialization and cleanup Take care of dangling pointers Keep track of dynamically allocated objects shared by multiple owners
Digitech Technologies
206
Smart Pointers
void abc() { demo *p(new demo); p->doSomething(); delete p; } void abc() { demo *p; try { p=new demo; p->doSomething(); delete p; } catch(){} void abc() { auto_ptr<demo> *p(new demo); p->doSomething(); }
Digitech Technologies
207
class employee { public: virtual void show() { cout<<"from employee\n"; } }; class manager : public employee { public: void show() { cout<<"from manager\n"; } };
Digitech Technologies
212
manager
213
Digitech Technologies
214
Digitech Technologies
215
Digitech Technologies
216
vector
Map/multimap deque
list
Digitech Technologies
217
vector example
Output 45 59 45 59 45 59 45 59
22 88 88 78
78 14 78 14 78 14 14
Output 14 78 45 59 22
220
l.push_back(45); l.push_back(59); l.push_back(22); l.push_front(78); l.push_back(14); list<int>::iterator it=l.begin(); for(int i=0;i<l.size();i++) { cout<<*it<<" "; it++; }
Digitech Technologies 221
/* Output 78 45 59 22 14 78 45 59 22 14 */
Digitech Technologies
222
set example
Output 14 22 45 59 78
224
set example
} /* Output 12 34 36 44 44 56 78 78 90 95 */
Digitech Technologies 228
Value:34
Digitech Technologies 229
Digitech Technologies
230
} Output 12 34 36 44 44 56 78 78 90 95 95 90 78 78 56 44 44 36 34 12 95 90 78 78 56 44 44 36 34 12
Digitech Technologies
232