Oops

200
Typical Structure of POP Programs Main Program Function - 1 Function - 5 Function - 4 Function - 3 Function - 2 Function - 6 Function - 8 Function - 7

description

hgd

Transcript of Oops

  • Typical Structure of POP Programs

    Main ProgramFunction - 1Function - 5

    Function - 4

    Function - 3

    Function - 2

    Function - 6

    Function - 8

    Function - 7

  • Relationship of data and functions in POPGlobal DataGlobal DataLocal DataFunction - 1Local DataFunction - 2Local Data

    Function - 3

  • Procedural Oriented Programming

    Emphasis is on doing things.Large programs are divided into smaller programs known as functions.Most of the functions share global data.Data move openly around the system from function to function.Functions transform data from one form to another.Employs top-down approach.

  • Disadvantages of POP

    Global data are more vulnerable to changes by a function. In large program it gets very difficult to identify what data is used by what functions.Incase we need changes in an external data structure, we need to revise all functions that access that data structure.Complexity increases.It does not model real world problems very well.

  • Organization of data and functions in OOP

    Data

    Functions

    Data

    Functions

    Data

    Functions

  • Object Oriented Programming

    Emphasis is on data rather than on procedure.Programs are divided into what are known as objects.Data structures are designed such that they characterize the objects.Functions and data are tied together.Data is hidden and cannot be accessed by external functions.Objects communicate with each other through functions.Changes and additions can be easily achieved.Follows bottom-up approach.

  • Object Oriented Programming

    Basic ConceptsObjectsClassesData abstraction and data encapsulationInheritancePolymorphismDynamic BindingMessage passing

  • Object Oriented Programming

    ClassesUser defined data type designed to solve a particular problem.Collection of objectsIt contains set of data and functions which manipulate over the data.

  • Object Oriented Programming

    ObjectsObjects are basic runtime entities.They are variables of type class.They are declared as class-name var-name.If fruit is a class and mango is an object then the syntax is : fruit mango.

  • Object Oriented Programming

    Data EncapsulationThe wrapping up of data and functions in the same unit .Data is not accessible to the outside world.This insulation of data is called data hiding.

  • Object Oriented Programming

    Data AbstractionAct of representing essential features without including background features.Classes use the concept of data abstraction so they are also called abstract data types (ADT).

  • Object Oriented Programming

    InheritanceProcess by which objects of one class acquire the properties of another class.Main advantage is reusability.

  • Object Oriented Programming

    PolymorphismGreek word which means ability to take many forms.Using plus sign with numbers gives sum where as with two strings yields concatenated string.

  • Object Oriented Programming

    Two categories of languages : Object Based Languages - Data encapsulation - Data hiding and access mechanism -Operator overloading e.g.:- Visual Basic , Ada.Object based Languages - Object Based features + - Inheritance - Dynamic Binding. e.g.:- C++, Java, Smalltalk , Object Pascal.

  • Insertion OperatorsInsertion operator or put to operator
  • Extraction Operator

    The extraction operator or the get from operator >> extracts the value from the keyboard and assigns it to the variable on the right.int a;cin >> a;Since it extracts data from the user it is called the extraction operator.

  • Structure of C++ ProgramInclude FilesClass DeclarationMember function definitionsMain function program

  • IdentifiersThey are names of names of variables, arrays , functions and classes.Naming identifiers - alphabets, digits and underscore are permitted - Cannot start with digit - Upper case and lower case are distinct. - Keyword cannot be used. - no limit to the length , while it is 32 in C.

  • C++ Data Types

  • KeywordsFixed words having fixed meaningsExample : int , float , etc.

  • Enumerated Data TypeUser defined type that provides a way of attaching names with numbers.Example : enum shape { circle , square , triangle }; shape is a new data type now.variables of this type can be created now.Circle is assigned the value 0 by default , square 1 and so on.

  • Enumerated Data TypeEnum colour { red , blue = 9 , green ,yellow};Here red = 0 , blue = 9 , green = 10 and yellow = 11.Color background = blue; // allowedColor background = 7; //errorColor background = (colour) 7;

  • PointersPointers are variables that store addresses of other variables as values.int a = 10;int *ptr;ptr= &a;Here 2 bytes is allocated for ptr and 2 bytes for a. In ptr &a is stored whereas in address of a 10 is stored.

  • Reference VariablesA reference variable provides an alias or an alternative name for an already existing variable.float total = 100;float &sum = total;

  • Operators

  • Precedence and AssociativityPrecedence is the priority level of operators.When we have more than one operators of the same precedence , associativity is considered,

  • Casting

  • Decision Making and BranchingSimple If StatementIf( condition is true){instruction -1;instruction -2;..}

    instruction -3;

  • Accessing Global Variableint i = 10;void main(){int i =20;{int i = 30;cout
  • new and delete operatorsnew operatorUsed to allocate memory space dynamically.Syntax : int *p = new int;int *p = new int(5); assigns value 5int *p = new int[5]; creates 5 variables.

  • delete operatordelete operatorUsed to release memory space dynamically.E.g.: delete p;int *p = new int[5];delete [] p;The brackets denote that p was pointing toan array.

  • Decision Making and BranchingSimple If StatementIf( condition is true){instruction -1;instruction -2;..}

    instruction -3;

  • Decision Making and BranchingIf Else StatementIf( condition is true){instruction -1;instruction -2;..}else{instruction -3;..}instruction -4;

  • Decision Making and BranchingElse if ladderIf( condition){ .. }else if (condition){ .. } else if( condition) { .. }else{..}

  • Decision Making and BranchingNested if elseIf( condition){ .. if( condition) { .. }else { .. }}else if (condition){ .. }

  • Decision Making and BranchingSwitch Statementswitch (expression){case 1:instruction-1;break;case 2:instruction-2;break;default:instruction-2;break;}

  • Decision Making and Looping3 steps of looping.Initialization- assigning an initial value to the control variableCondition checking checking the condition and then executing the instructions in the body of the loop.Incrementation or decrementation.

  • Decision Making and LoopingWhile loopPrint 1 to 10 numbers using while loopint I = 0; // initialization while (I
  • Decision Making and Loopingfor loopPrint 1 to 10 numbers using while loopfor(i=0;i
  • Decision Making and LoopingDo While loopPrint 1 to 10 numbers using do while loopint I = 0; // initialization do // condition checking{cout
  • Decision Making and Looping

  • FunctionsSubprogramsSet of finite instructions written down to accomplish a specific task.Reduces complexity.Up gradation becomes comparatively easy.Debugging becomes easy.

  • FunctionsThree partsDeclarationreturn-type func-name( type of arg);int add( int , int);Definitionint add( int a, int b){ return (a+b); }Callingsum = add (x,y);

  • Difference between call by pointers and call by referencesCall by pointersvoid swap (int * , int *);void swap (int *p, int *q){int temp;temp = *p;*p = *q;*q = temp;}swap (&a,&b); //calling

    Call by referencesvoid swap (int & , int &);void swap (int &ra, int &rb){int temp;temp = ra;ra = rb;rb = temp;}swap (a,b); //calling

  • Default Argumentsfloat s_interest(int p,int y,int rate = 2);float s_interest(int p,int y,int rate ){int interest = p*rate*y/100;return interest}s_interest(1000,5); //callings_interest(1000,5,4); //calling

  • ClassesClass specification has two parts-Class declaration describes the type and scope of its membersClass function definition.describe how the functions are implemented.

  • Classesclass class-name{private:variable declarations;function declarations;public:variable declarations;function declarations;};

  • Data hiding in classesDataFunctionsDataFunctions

    Private areaNoAccessFrom outside Public areaAccessFrom outside allowed

  • Classes

    Class item{private:int number;int cost; public :void getdata( int c,int no) //definition{ cost = c; number = no;}void putdata( ) //definition{ cout

  • Creating ObjectsObjects are variables of type class.So the syntax is class-name object-name;Objects can call all the members functions.Syntax :Object.function-name();

  • Creating objectsvoid main(){item earPhones;earPhones.getdata(10,1000);// function callearPhones.putdata();// function call}

  • Memory Allocation When a class is defined memory is allocated partially.Memory for functions is allocated once when the class is defined.Sum of memory space of all data members is allocated when an object is created.Every object has a separate set of data members.

  • Memory allocation for objectsclass car{int cost, avg;float speed;public:..functions..};void main(){test city, accord;}Here 16 bytes of data is allocated .8 bytes for object city and 8 bytes for object accord.costavgspeedcostavgspeedcityaccordfunctions

  • Static VariablesData members of a class that are created just once.The same copy is accessed by all the objects of that class.Since they are created at the class level they are also called class variables.They are initialized to 0.

  • Static Data Members

  • Static Data Membersclass test{int I;static int x;//declaration};int test :: x;//definition

  • Static Member FunctionsMembers which are declared as static have the following properties-

    Can access only static members variables.

    Can be called using the class name.class test{int x,y,z;static int count;public:static void func(){count++;x++; //error}};Void main(){test func();// call}

  • Arrays of Objectsclass test{int x,y,z;static int count;public:functions..};Void main(){test t[3];}

    countx,y,zx,y,zx,y,zt[0]t[1]t[2]

  • ConstructorsSpecial member function whose task is to initialize the objects of its class.They have the same name as the class name.They are called automatically when objects are created.

  • ConstructorsThere are three types-Default constructor- does not have arguments.-is called automatically

    Parameterized constructorCopy constructor

  • Default ConstructorsDefault constructor- does not have arguments.- is called automatically when an object is created.class xyz{int a;public:xyz();};void xyz :: xyz() { a = 0;

    void main(){xyz obj1;}

  • Parameterized ConstructorsParameterized constructor- takes arguments.- is called automatically when an object is created.class xyz{int a;public:xyz();xyz(int);};void xyz :: xyz() { a = 0;}void xyz :: xyz(int x){a = x;}

    void main(){xyz obj1(5);//implicit call to parameterized constructorxyz obj2 = xyz(10);//explicit call}

  • Copy ConstructorCopy constructor- used to copy an object to another - takes reference of its type as an argumentclass xyz{int a;public:xyz();xyz(int); xyz(xyz &); // declaration};void xyz :: xyz() { a = 0;}

    void xyz :: xyz(xyz &temp){a = temp.a;}

    void main(){xyz obj1 xyz obj2(obj1);xyz obj3 = xyz(obj1);//explicit call}

  • Points to note about constructorsShould be declared in the public sectionInvoked automatically when objects are createdDon't have return types not even void.Cannot be inherited.They can have default arguments.Cannot be virtual.Objects with constructors cannot be used as members of unions.Make implicit calls to new and delete.

  • DestructorsMember function whose name is same as the class name.Used to destroy the objectsCannot return any value not even void.Cannot take arguments.Preceded by a tilde~ sign.

  • Destructorsclass alpha{public: alpha(){count++;cout
  • DestructorsWhen any object gets out of scope the destructor is implicitly called.Objects are destroyed in the opposite order of their creation.

  • InheritanceInheritanceProcess by which objects of one class acquire the properties of another class.Main advantage is reusability.

  • Types of InheritanceTypes-Single InheritanceMultiple InheritanceHierarchical InheritanceMultilevel InheritanceHybrid Inheritance

  • Types of InheritanceSimple InheritanceHierarchical inheritance

  • Types of InheritanceMultiple InheritanceMultilevel InheritanceClass 2Class 3Class 1Class 2Class 3

  • Types of InheritanceClass 1Class 2Class 3Class 4Hybrid Inheritance

  • Single InheritanceSuppose B is the base class.We want to create a class D derived from B.Syntax for deriving it is : class der-class-name : mode base-class-nmode private , protected , public.

  • Single Inheritance - publicclass B{ int a;public :int b;};class D : public B{ int x;public:func();};private : apublic : bClass Bprivate : xpublic : b , func()

    Class D

  • Single InheritanceProtected data membersclass B{ int a;protected : int y;public :int b;};class D : public B{ int x;public:func();};private : aprotected : ypublic : bClass Bprivate : xprotected : ypublic : b , func()

    Class D

  • Single Inheritance - privateclass B{ int a;public :int b;};class D : private B{ int x;public:func();};private : apublic : bClass Bprivate : x,bpublic : func()

    Class D

  • Single Inheritance - protectedclass B{ int a;protected: int y;public :int b;};class D : protected B{ int x;public:func();};private : aprotected : ypublic : bClass Bprivate : xprotected : b , ypublic : func()

    Class D

  • InheritanceBase Class visibility

    Private

    Protected

    Public

    Not Inherited

    Protected

    Public

    Not Inherited

    Private

    Private

    Not Inherited

    Protected

    Protected

    Mode of inheritancePrivate Protected Public

  • Multiple Inheritanceclass B1{..};class B2{..};class B3{..};class D : private B1, protected B2, public B3{ .. };void main(){ .. }

  • Resolving ambiguityclass B1{public: display();};class B2{public: display();};class D : public B1,public B2{ .. };void main(){D obj;obj.display(); // errorobj.B1::display();obj.B2::display();}

  • Hybrid Inheritanceclass Parent{ public : calc();};class child1 : public virtual Parent {..};class child2 : virtual public Parent{ .. };class grandchild : public child1,public child2{}void main(){ grandchild gc; gc.calc();}

  • Inheritance with Default Constructorsclass base{int a; public: base(){ cout
  • Inheritance with Parameterized Constructorsclass base{int a; public:base(){} base(int aa){ a = aa;cout
  • Composition vs InheritanceHaving an object of a class as a member of another class is called composition.An object of wheel class will be a member of the car class.we can say that car has a wheel.Composition exhibits has-a relationship.Object of one class obtaining the properties of an object of another class is called inheritance.Suppose car class inherits from vehicle class.Then we can say that car is a vehicle.Inheritance exhibits is-arelationship.

  • Composition Syntaxclass X{ int a;public: void ass(int aa){ a = aa ;}void get(){ return a ;}};Class Y{ int a;public:X x;

    void ass(int aa){ a = aa ;}void get(){ return a ;}};void main(){Y y;y.ass(10);y.x.ass(20);y.get();y.x.get();}Output : 10 20

  • Friend FunctionsIn cases when we want the non memberfunctions to access the private of a class We declare those functions as friend.Three types : A global function declared friend of a class.Member function of one class as friend of another class.A class as a friend of another.

  • A global function declared friend of a class.class sample{ int a,b;public: void setvalue() { a = 25;b = 50;} friend float mean(sample s);};float mean(sample s) {return((s.a + s.b)/2);}int main(){sample x;x.setvalue();cout
  • A global function declared friend of two classesclass ABC; // forward declarationClass XYZ{ int x;public: void setvalue(int i) { x = i;} friend void max(XYZ,ABC);};void max(XYZ m,ABC n){if(m.x > n.a ) cout
  • Member function of one class as friend of another class.class X{ int fun1();};class Y{ friend int X :: fun1();..};

  • A class as a friend of another.class X{ int fun1();};class Z{friend class X;};Here class Z can access the private of class X.Vice versa is not true.

  • Things to note about friend functions.They are not in the scope of the class.They cannot be called using an object.Cannot access the member names without the object.Can be declared in the private or public region without affecting its meaning.Usually it has objects as arguments.

  • Inline Functions

    Functions which are expanded in line whenthey are invoked.

    That is that compiler replaces the function call with the corresponding function code.

  • Inline FunctionsTwo ways of declaring a function as inline.Define the function inside the class.class abc{public :void func(){ ..}// inline function};With the keyword inlineClass abc{public:void func();};inline void func(){}

  • Advantages and DisadvantagesAdvantagesSpeed increases. But as size increases the advantages diminish. DisadvantagesIt takes up more memory space.

  • Inline FunctionsInline keyword is a mere request to the compiler.Situations where inline functions may not work :- if a loop , switch or goto is used.- functions not returning values, if a return statement exists.- functions contain static.- functions are recursive.

  • Polymorphism

    Greek term meaning one thing taking multiple forms.Must know terms- early binding/static linking- late binding/dynamic linking

  • PolymorphismPolymorphismCompile time polymorphismRun time polymorphism

    Function OverloadingOperatorOverloadingVirtual Functions

  • Function OverloadingWhen more than one function has the same name but different number and type of arguments, it is called function overloading.Depending on the number of arguments specified during function call the respective function is executed.The linking takes place at compile time so it is called early binding or static linking.

  • Function Overloadingint vol(int r){return (r*r*r);}int vol(int r,int h){return(3.14*r*r*h);}int vol(int l,int b,int h){return (l*b*h);}

    void main(){int cube , cylinder, cuboid;cube = vol(5);cylinder = vol(5,3);cuboid = vol(6,7,4);}Here there are 3 functions with the same name but different number of arguments.

  • Constructor OverloadingHere there are three functions constructors with the same name but different arguments. This is called constructor overloading.class xyz{int a;public:xyz();xyz(int); xyz(xyz &); // declaration};void xyz :: xyz() { a = 0;}

    void xyz :: xyz(xyz &temp){a = temp.a;}

    void main(){xyz obj1 xyz obj2(obj1);xyz obj3 = xyz(obj1);//explicit call}

  • Operator Overloading

    The mechanism of giving special meaning to an operator is called operator overloading.

    We can almost create a new language of our own by overloading operators.

  • Operator Overloading

    The following are the operators that cannot be overloaded.Class member access operator . or *.Scope resolution operator ::Size operator (sizeof)Conditional operator (?:)

  • Operator OverloadingOperator overloadingUnaryoperatorsBinaryoperatorsMemberfunctionFriendfunctionMemberfunctionFriendfunctionNoargumentOneargumentOneargumentTwoargument

  • Overloading unary operators using member functionsclass space{int x,y,z;public :void get(int a,int b,int c){ x = a; y = b; z = c;}void display(){..}void operator-();};void space :: opertor-(){ x = -x; y = -y; z = -z;}

    void main(){space s;s.get(3,-6,9);s.display();-s;s.display();}Output:X = 3, y = -6; z = 9X = -3, y = 6; z = -9

  • Overloading unary operators using member functionsSince this function is the member of the class the data members can be accessed directly .A statement likes2 = -s1; would not work becausethe function does not return any value.If modified to return an object it can work.

  • Overloading unary operators using friend functionsclass space{int x,y,z;public :void get(int a,int b,int c){ x = a; y = b; z = c;}void display(){..}friend void operator-(space&);};void operator-(space &s){ s.x = -s.x; s.y = -s.y;s.z = -s.z;}

    void main(){space s;s.get(3,-6,9);s.display();-s;s.display();}Output:X = 3, y = -6; z = 9X = -3, y = 6; z = -9

  • Overloading unary operators using friend functionsHere the function being a friend function, it isnot a member of the class, so the privatemembers of object are not accessiblewithout the object name from the friendfunction.

    So the object has to be passed as anargument.

  • Overloading binary operators using member functionsclass complex{float imag , real;public: complex(){..} complex (float r, float I){ x = r; y = i;}complex operator+ (complex);void display(){ cout
  • Overloading binary operators using member functionscomplex complex :: operator+ (complex c){complex temp;temp.real = real + c.real;temp.imag = imag + c.imag;return temp;}void main(){complex c1,c2,c3;c3 = c1 + c2; //c3 = c1.operator+(c2);c3.display();}

  • Overloading binary operators using member functions

    Note the following features of this function :It receives only one complex type argument.It returns a complex type value. That is it returns an object.It is a member function of the class complex.

  • Overloading binary operators using Friend functionscomplex operator+ (complex c1 , complex c2){complex temp;temp.real = c1.real + c2.real;temp.imag = c1.imag + c2.imag;return temp;}void main(){complex c1,c2,c3;c3 = c1 + c2; // c3 = operator+(c1,c2);c3.display();}

  • Rules for overloading operatorsOnly existing operators can be overloaded.The overloaded operator must have at least one operand which is of the user defined type.We cannot change the basic meaning of the operator.Overloaded operators follow the syntax rules of the original operators.They cannot be overridden.There are some operators that can not be overloaded.

  • Rules for overloading operatorsThose operators are - -size of operator sizeof -membership operator . , *.-scope resolution ::-conditional operator ?:We cannot use friend functions while overloading the following operators.- assignment operator =-function call operator ()-subscripting operator []-class member access operator ->

  • Rules for overloading operatorsUnary operators when overloaded using member functions take no explicit arguments , but those overloaded with friend functions take one explicit argument- the object of the relevant class.Binary operators when overloaded using member functions take one explicit argument , but those overloaded with friend functions take two explicit arguments - the objects of the relevant class.

  • Runtime polymorphismAt runtime when it is known what class objects are under consideration , the appropriate version of the function is invoked. Since the function is linked with a particular class much later after the compilation , this process is termed as late binding. It is also known as dynamic binding because the selection of the appropriate function is done dynamically at run time.

  • Runtime polymorphismRun rime polymorphismis achieved usingPointersclass item{int code , price ;public : void getdata(int c, int p){code = c; price = p;}void display(){cout
  • Pointer to array of objectsvoid main(){item it[3];item *p;p = it;int code,price;for(int i=0;i>price;p->getdata(code,price);p++;}

    p = it;for(int i=0;idisplay();p++;}}

    Here we are using pointer to array of objects.When we use pointers to access class members -> operator is used instead of the .(dot ) operator.

  • Array of Pointer to objectsvoid main(){item it;item *p[5];int code, price ,option , i=0;do{p[i] = new item;coutcode>>price;p[i]->getdata ( code, price);i++;}while(i
  • this pointer

    This unique pointer is automatically passed to a member function when it is called.The pointer this acts as an implicit argument to all the member function.It points to the implicit object.

  • this pointerclass person{char name[20];float age;public:person( char *s , float a){strcpy ( name , s);age = a; }person & person :: greater( person &x){if( x.age >= age)return x;elsereturn *this}

    void display(){cout

  • Pointers to Derived Objectsvoid main(){BC *bptr , base;bptr = &base;bptr->b = 100;bptr->show();

    DC derived;bptr = &derived;bptr->b = 200;bptr->d = 300; //wont workbptr->show();

    }class BC{ public: int b; void show(){cout

  • Pointers to Derived ObjectsWhen we use a base class pointer , make it point to derived class object , and then call a function which is present in both base and derived class , the base class function gets called.We cannot use this base class pointer pointing to the derived class object to access members of the derived class.

  • Virtual Functionsclass BC{ public: int b;virtual void show(){cout
  • Rules for Virtual FunctionsMust be members of some class.Cannot be static members.Are accessed by using object pointers.Can be a friend of another class.Virtual function should be defined in the base class ,even though it might not be used.The prototypes of the function in the base class and in the derived class must be same.We cannot have virtual constructors but we can have virtual destructors.

  • Rules for Virtual Functions

    A base class pointer can point to any type of derived object , but the reverse is not possible.The incrementation or decrementation operator cannot be used with base class pointer ,pointing to derived object , to point to the next object.

  • Rules for Virtual Functions

    If a virtual function is defined in the base class, it need not be necessarily redefined in the derived class. In such cases, calls will invoke the base function.

  • Pure Virtual FunctionsThe function inside the base class is seldom used for performing any task.It only serves as a placeholder.Such functions are called do nothing functions. They can be defined asvirtual void display() = 0;Such functions are called pure virtual functions.

  • Abstract base classA class that has at least one pure virtualfunction is called an abstract base class.The main objective of an abstract base classis to provide some traits to the derivedclasses and to create a base pointerrequired for achieving run timepolymorphism.An object of the ABS cannot be created.

  • TemplatesTemplates a new concept which enables us to define generic classes and functions and thus provides support for generic programming.Generic programming is an approach where generic types are used as parameters in algorithms so that they work for a variety of suitable data types and data structures.A template can be used to create a family of classes or functions.

  • Templatesclass vector{int *v,size; public :vector(int m){v = new int[size = m];for(int I = 0; i
  • TemplatesTemplateclass vector{T *v,size; public :vector(int m){v = new T[size = m];for(int I = 0; i
  • TemplatesTemplateclass vector{T *v,size; public :vector(int m){v = new T[size = m];for(int I = 0; i
  • Two Generic Data Types in a Class Definitiontemplateclass test{t1 a;t2 b;public:test(t1 x, t2 y){ a = x; b = y;}void show(){ cout
  • Function Templatetemplatevoid swap(T &x , T &y){T temp = x;x = y;y = temp;}int main(){float a,b;int x,y;swap(a,b);swap(x,y);}

  • Functions with Two Generic Data Typestemplatevoid display( t1 x, t2 y){cout
  • Template function with explicit functiontemplatevoid display(t x){cout
  • Resolution of overloaded template or ordinary functionsA template function may beoverloaded either by templatefunction or an ordinary function.The overloading resolution may be resolved as follows:Call an ordinary function which has an exact match.Call a template function that can be created by an exact match.Try normal overloading resolution to ordinary functions and call one that matches.

  • Non type template argumentsTemplate class array{T a[size];}; void main(){array a1;array a2;array a3;}

  • Exception HandlingExceptionsPeculiar problems other than logic and syntax errors.Run time anomalies or unusual conditions that a program may encounter while executing.Anomalies might include conditions like division by zero , access to an array outside bounds, etc.

  • Exception HandlingExceptions are of 2 types : Synchronous exceptionserrors such as out of - range or overflow2. Asynchronous exceptionserrors caused by events beyond the control of the program such as keyboard interrupt.The exception handling mechanism in C++ is designed to handle only synchronous exceptions.

  • Synchronous Exceptions MechanismTry blockDetects and throws An exceptionCatch blockCatches and handlesthe exceptionExceptionobject

  • Exceptions Handling MechanismC++ exception Handling Mechanism is basically built on 3 keywords : try , throw and catch.Try1.The keyword try is used to preface a block of statements which may generate exceptions. This group of statements is called try block.

  • Exceptions Handling MechanismThrowWhen an exception is detected it is thrownusing throw keyword in the try block.CatchA catch block defined by the keyword catch catches the exception thrown by the throw statement in the try block and handles it appropriately.

  • Exceptions Handling Mechanism.try{.//block of statements which detectsthrow exception; // and throws an exception.}catch(type arg) //catches an exception{..//block of statements that handles}// the exception

  • Exceptions Handling Mechanismint main(){int a,b;couta;cin>>b;int x = a-b;try{if(x!=0)cout
  • Function Invoked by try block throwing exceptionThrow point Function thatcauses anExceptionTry blockInvokes a function that contains anExceptionThrow ExceptionCatch blockCatches and handlesthe exceptionInvoke function

  • Function Invoked by try block throwing exceptiontype function(arg list) //function with exception{throw(object)//throws exception}try{. //invokes the function}catch(type arg) //catches an exception{.. // the exception}

  • Multiple Catch blockstry{. //invokes the function}catch(type1 arg) //catches an exception{.. //catch block 1}catch(type2 arg) //catches an exception{.. // catch block 2}catch(typeN arg) //catches an exception{.. // catch block N}

  • Catch all ExceptionsIn some situations we may not be able toanticipate all possible types of exceptionsand therefore may not be able to design allpossible catch handlers.In such situations we can force allExceptions-catch(){.//statements for processing all exp.}

  • Working With FilesFileFile is a collection of related data stored in aparticular area on the disk.Need of filesMany real life problems handle largevolumes of data and in such situations weneed to store it in hard disk. The data isstored in these devices using the concept of files.

  • Kinds of Data CommunicationA program may include either or both kindsof data communication.Data transfer between console unit and the program. using cin and cout objects.Data transfer between the program and the disk file.- making use of files.

  • Kinds of Data CommunicationExternal MemoryData FilesProgram + DataConsole UnitScreen and KeyboardProgram File interactionConsole program interactionWrite dataTo filesGet data fromthe keyboardRead datafrom fliesWrite dataOn output screenConsole-program-file interaction

  • Input and Output StreamsInput StreamThe stream that provides data to theprogram is called input stream.It extracts or reads data from the file.Output StreamThe stream that receives data from theprogram is called output stream.It inserts or writes data onto the file.

  • File Input and Output StreamsInput StreamOutput StreamProgramDisk FilesRead dataWrite DataData OutputData InputFile Input and Output Streams

  • Stream Classes for file Operationsiosistreamstreambufostreamifstreamfstreamofstreamiostreamfstream basefilebufiostream filefstream file

  • Details of File Stream Classesfilebuf Its purpose is to set the file buffers to readand write. Contains open() and close() asmembers.fstreambaseProvides operations common to the filestreams. Servers as a base for fstream ,ifstream and ofstream class.

  • Details of File Stream ClassesifstreamProvides input operations . Contains open()with default input mode. Inherits get() ,getline() , read() , seekg() and tellg()functions from istream.ofstreamProvides output operations. Contains open()with default output mode. Inherits put() ,write() , seekp() and tellp()functions from ostream.fstreamProvides support for simultaneous input and output operations.

  • Opening a FileOne needs to decide the following thingswhile opening a file Suitable name of the file.Data type and data structure.PurposeOpening method.

  • Opening a FileA file can be opened by two ways Using the constructor functionUsing the member function open() of the class.

  • Opening a File with Constructors.This involves 2 steps-Create a file stream object to manage a stream using the appropriate class. That is ofstream class to create output stream and ifstream class to create input stream.Initialize the file object with appropriate file name.ofstream outfile(results);Opens a file named results for output.

  • Reading and Writing in a Fileofstream outfile(results);ifstream infile(test);outfilenumber;Here we are reading from test file and writing into results file

  • Working with Single File using Constructorsint main(){ofstream outf(ITEM);// writing into file ITEMcoutname;outfname;inf.close(); //writing the read name on // the output screen.cout
  • Working with Multiple File using open() function.int main(){ofstream outf;outf.open(country);// writing into file Countryoutf
  • Open() file modeios::in - for reading onlyios::out - for writing onlyios::app - append to end of fileios::ate - go to end of file on opening.ios::nocreate open fails if file does not existios::noreplace opens files if the file already existsios::trunc -deletes the contents of the file if the file already exists.ios::binary - Binary File

  • File PointersEach file has two associated pointers knownas file pointersInput or get pointer. It is used for reading the contents of a given file.Output or put pointer. It is used for writing to a given file location.

  • Functions for Manipulation of File Pointersseekg()- moves the get(input) pointer to a specified locationseekg(offset, refposition);seekp()- moves the put(output) pointer to a specified locationseekp(offset, refposition);tellg() gives the current position of the get(input ) pointertellp() gives the current position of the put(output ) pointer

  • Functions for Manipulation of File PointersThe refposition takes one of the followingthree constants ios::beg - start of the fileios::cur - current position of the fileios::end - end of the file

  • Functions for Manipulation of File PointersSeek callActionfout.seekg(0,ios::beg) go to startfout.seekg(0,ios::cur) stay at the current location.fout.seekg(m,ios::beg) move to (m+1)th byte from the beg.fout.seekg(-m,ios::end) go backward by m bytes from the end

  • io operations on Binary Files.write() and read( functionsThey handle data in the binary mode.Syntax- infile.read((char*)&V , sizeof(V));outfile.write((char*)&V , sizeof(V));Both these functions take two arguments1. address of the variable V2. no of bytes occupied by it.

  • Reading and Writing Class Objectsclass student{int rno;char name[20];public:void read();void display();};void student::read(){coutrno;coutname;}void student::display(){cout
  • Reading and Writing Class Objectsvoid main(){student s[3];ofstream outf;outf.open(students);cout
  • Operations on a file containing recordsThe following are the important operationsthat have to be performed on the file Writing records in the file.Reading records from the file.Modifying an existing record from a file.Adding a new item to a file.Deleting an existing item.

  • Error Handling With filesOne of the following things may happenwhen dealing with filesA file being opened for reading does not exist.A filename used for a new file already exists.Reading past end of file.No space in the memory for creating more files.Using invalid file name.Trying to perform an operation for which we have not opened the file.

  • Error Handling FunctionsFunctionReturn value and meaning

    eof()returns true if EOF has been encountered while reading otherwise returns false.fail()returns true if an input or an output operation has failed.

  • Error Handling FunctionsFunctionReturn value and meaning3. bad()returns true if an invalid operation has occurred or unrecoverable operation has occurred, returns false if a recoverable operation has occurred.4. good()returns true if no error has occurred and false when no further operations can be further carried out.

  • Error Handling Functionsifstream infile;infile.open(ABC);while(!infile.fail()){//process the file.}if(infile.eof()){//terminate program //normally}

    else{if(infile.bad()){//report fatal error}else{infile.clear();}}clear() resets the error state sothat further operations can beattempted.

  • Standard Template LibraryThe collection of generic classes and functions is called standard template library. (STL)STL contains several components. But at its core are three key components 1. Containers2. algorithms3. iterators

  • Standard Template LibraryContainerIt is an object that actually stores data.It is a way data is organized in memory.The STL containers are implemented by template classes and therefore can be easily customized to hold different data types.

  • Standard Template LibraryAlgorithmIt is procedure that is used to process data contained in the containers.STL includes many different kinds of algorithms to provide support to tasks such as initializing , searching , copying , sorting , merging.Algorithms are implemented using template functions.

  • Standard Template LibraryIterators it is an object that points to an element in a container.They are used to move through the contents of the container.Iterators are used just like pointers. We can increment and decrement them.They connect algorithms with containers and play a key role in manipulation of data stored in the containers.

  • Categories of ContainersContainersSequenceContainers

    VectorDequeList

    AssociativeContainers

    Set mapMultisetMapMultimapDerived Containers

    StackQueuePriority queue

  • ContainersVector A dynamic array.Allows insertions and deletions at back.Allows direct access to any element.Header file - Iterator random access.

  • ContainersListA bidirectional ,linear list.Allows insertions and deletions anywhere.Header file - Iterator bidirectional.

  • ContainersDequeA double ended queue.Allows insertions and deletions at both the ends.Permits direct access to any element.Header file - .Iterator random access.

  • ContainersSetAn associative container for storing unique sets.Allows rapid look up.Header file - .Iterator bidirectional.

  • ContainersMultiset An associate container for storing non unique sets.No duplicates allowed.Header file - .Iterator bidirectional.

  • ContainersMapAn associate container for storing unique key/value pairs. Each key is associated with only one value.One to one mapping.Allows key based look up.Header file - .Iterator bidirectional.

  • ContainersMultimapAn associate container for storing key/value pairs. Each key is associated with more than one value.One to many mapping.Allows key based look up.Header file - .Iterator bidirectional.

  • ContainersStack A standard stack. Last in first out (LIFO).Header file - .No iterator.Queue A standard queue. First in first out (FIFO).Header file - .No iterator.

  • ContainersPriority queueA priority queue.The first element out is always the highest priority element. Header file - .No iterator.

  • Comparison of sequence ContainersContainer random I/D in I/D at end access middle

    Vector fast slow fast at backList slow fast fast at frontDeque fast slow fast at both ends

  • Associative ContainersThey are designed to support direct access to elements using keys.They are not sequential.There are four types SetMultisetMapMultimap

  • Derived ContainersThe STL provides three derived containersnamely stack , queue and priority_queue.These are also known as container adapter.Stack , queue and priority_queue can be created from different sequence containers. The derived containers do not support iterators and therefore we cannot use them for data manipulation.They support two functions push() and pop() for performing deleting and inserting operations.

  • Algorithms They are functions that can be used across a variety of containers for processing their contents.STL algorithms reinforce the philosophy of reusability.We must include in our program.

  • IteratorsThey behave like pointers and are used to access container elements.They are often used to traverse from one element to another , a process known as iterating through the container.

  • IteratorsThere are five types of iterators Input 1.Access method linear2. Direction of movement forward only3. I/O capability read only4. Remark cannot be saved

  • IteratorsThere are five types of iterators Output 1.Access method linear2. Direction of movement forward only3. I/O capability write only4. Remark cannot be saved

  • IteratorsThere are five types of iterators Forward 1.Access method linear2. Direction of movement forward only3. I/O capability read/write only4. Remark can be saved

  • IteratorsThere are five types of iterators Bidirectional 1.Access method linear2. Direction of movement forward and backward3. I/O capability read/write4. Remark can be saved

  • IteratorsThere are five types of iterators Random 1.Access method random2. Direction of movement forward and backward3. I/O capability read/write4. Remark can be saved