> cin>>k> k>>b >b;; int p, q; } public: void c :: put4() void get3(); void put3(); { cout cout<< <<”k ”k=” =”<< <
CHAPTER – 8 POINTERS ADDRESSES AND POINTERS A Pointer is a variable that holds the address of the location of another variable in the main memory of the computer. A pointer provides a way of accessing a variable without referring to the variable directly. Pointers are used when passing actual values is difficult or undesirable. Some reasons to use pointers are as follows: • To return more than one value from a function. • To pass arrays and string more conveniently from one function to another. • To manipulate arrays more easily by moving pointers to them, instead of moving the arrays themselves. • To create complex data structures, such as linked lists and binary trees where one data item must contain references to other data items. • To communicate information about memory as in the function delete() which returns the location of free memory by using a pointer. Address of Operator (&) and Pointer Variables: - The operator ‘&’ is used to get the address f a variable. Program to demo the use of &. #include
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++ #include
CHAPTER – 9 VIRTUAL FUNCTIONS POLYMORPHISM It includes the ability to use the same message to objects of different classes and make them behave differently. Thus we could define “+” for both the addition of numbers and the concatenation of characters, even through both these operations are completely different, thus, polymorphism provides the ability to use the same word to invoke different methods/action according to similarity of meaning. It allows the programmer to define a base class that includes routines that perform standard operations on groups of related objects, without regard to the exact type of each object. There are two types:
1. Comp Compil ilee time time poly polymo morp rphi hism sm: - The The over overlo load aded ed member member functi functions ons are “selec “selected ted for invoki invoking” ng” by matching the member of arguments and argumentstype. This information, viz. number of arguments types is known to the compiler at the compile time itself.
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++ 2.
Therefore, the selection of the appropriate function made the compile time only. This is known as early binding or static binding. Run time polymorphis polymorphism m: - In run time polymorphis polymorphism, m, function function is blind with their object object at runtime not compile time. So that appropriate version of the function can be called run time polymorphism. It is also known as late binding.
VIRTUAL FUNCTION C++ use to use same function in different levels of class hierarchy. But we have to make function virtual function is the implementation of run time polymorphism. In run time polymorphism function is bin with their object at run time not compiling time. Program to achieve Run Time polymorphism/Late binding/Demo. Of virtual function #include
Output: C=0
C=0
C=0
C=3
C=3
C=3
invoked with class Static Member Function: - Static Member function can access the static member. Static member function is invoked name as: Class name :: function name() We know that static member is declared under class but it is not the part of any object. That’s why it needs to declare outside the class also as: datatype class name :: static member #include
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++ Friend function can be friend of one class and more than one class.
Friend Function Demonstration: - Example (1): #include
CHAPTER – 10 STREAMS STREAM CLASSES C++ uses the following classes to implement streams: • ios class: - This is the base class to the input and output stream classes. • istream and ostream classes: - These are derived class from the ios class and and poss posses es spec specia ializ lized ed inpu inputt and and output stream behaviour, resp respec ecti tive vely ly.. The The istr istrea eam m clas classs cont contai ain n such such func functi tion onss as get( get(), ), getline() and read() while the stream class ontain such functions as put() and write(). • iostream class: - This is derived from bot both h the the istr istrea eam m and and the the ostr ostrea eam m classes and provides input and output functions for reading from the keyboard and writing to the monitor. • fstream classes: - These classes provide input and output from files. The ifstream class is used for creating input file, ofstream class for output file and fstream for files that will be used for both input and output. These classes are derived from istream, ostrem, iostream and from fstreambase. STREAM CLASS HIERARCHY HEADER FILES A header file provides a centralized location for the declaration of all extern variables, function prototypes etc. program files that must use or define a variable or a function must include the corresponding header files. For example, for using I/O functions, we need to include iostream.h file at the beginning of a program. The header file “ fstream.h” provides support for simultaneous I/O operations. It contains the classes ifstream and ofstream that provide I/O operations.
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++ ios FLAGS C++ provides several methods for formatting the output. These are the following: Functions and flag defined in the ios class. Manipulators. User-defined output functions. The ios class defines formatting flags and error-status flags. Some of the following formatting flags are as follows: Skipws: - Skip whitespace on input. Left – left-adjusted output. Right – right-adjusted output. Dec – convert to decimal. Oct – convert to octal. Hex-convert to hexadecimal. Showos –display + before positive integers. Stdio – flush stdout, stderror after insertion. Scientific – print floating point number in scientific notation. Following are the error flags: goodbit – no errors. eofbit – reached end of file. failbit – operation failed. badbit – invalid operation. hardfail – unrecoverable error. STREAM MANIPULATORS Stream Manipulators are the following-instructions which are inserted directly into a stream. These can be used to set the formatting and displaying characteristics and other attributes of the stream objects. Come important manipulators are as follows: ws – turn on whitespace. ends – insert null character to terminate an output string. flush – flush the output stream. dec – convert to decimal. oct – convert to octal. hex – convert to hexadecimal. setw (int field-width) field-width) – set field width for output. output. setfill(int fill-character) – set fill character for output. set precision(int precision) – set preision. setiosflags(long formatting-flags) – set the specified flags. resetiosflags(long formatting-flags) – reset the specified flags. STRING STREAMS The program that read and write strings from/to disk files, is given below: #include
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++ kk<<”Delhi”; kk<<”Mumbai”; kk.close(); { ll.getline (ch, n); cout<
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++ ff<
} ffclose(); ff’close();
else ff’<
}
CHAPTER – 11 EXCEPTION HANDLING Exception handling provides a way of transferring control and information to an unspecified caller that has expressed willingness to handle exceptions of a given type. Exception of arbitrary types can be ‘throw and catch ‘and set of exceptions a function may throw can be specified. Exception handling handles run time errors. Mainly generated the run time errors are as follows:logical:- poor understanding of given problem and procedure of solution. Syntax :- poor understanding of programming language. Exception:- arises when program executed due to: Illegal arithmetic expression like digit divided by zero. Array overflow. Array index out of bound. Incompatible assignment etc. It mechanism transfers control and information from a point of exception in a program to an exception handler associated with the try block. An exception handler will invoked only by a thrown expression in the code executed by the handler’s try-block. C++ provides following keywords to deal with exception. These are:Try: - try is basically, a block where exception is generated. Throw: - when exception is generated, it must be ‘throw’ is used to throw the exception. ‘throw’ is used in ‘try’ block. Catch: - catch () is also a block, where exception handler statements are defined. It is basically a function & accepts exception that is thrown by throw. # program to demo. Exception handling void main() { int b,c; cout<<”enter value of b & c”; c”; cin>>b>>c; try{ if(c==0) throw c; else cout<>n; test(n); catch(char nm) } { cout<<”exception caught”<
CHAPTER – 12 CLASS LIBRARIES Class Libraries : - C++ provides a library of data structures. Standard C++ includes its own built-in container class library. String Class: - The string class stores the string as a character array and it includes a field that stores the size of the array. In order to use this this clas classs we we need need to to place place the statem statement ent:: #inclu #include< de
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++ Assi Assign gn() () To rese resett a stri string ng’s ’s valu values es base based d on a subs substr trin ing g of anot anothe herr str strin ing. g. Synt Syntax ax:: s1.a s1.ass ssig ign( n(s2 s2,1 ,1,2 ,2); ); Insert() To in insert a string in inside an another. Sy Syntax: s1 s1.insert(2, “v “vinod”); Resize() To ch change th the size of of st string. Sy Syntax: s1 s1.resize(20); Length() To de determine th the cu current le length of st string. Sy Syntax tax: in int le len = s1.length(); Find() To search a string for the position at which a substring starts. Stack Class: - The stack class operates much like the standard stacks. It is implemented as a template class, so we can make a stack a stack obje object ct of any any dat dataa typ type. e. In orde orderr to to use use this this clas classs we we nee need d to to plac placee the the stat statem emen ent: t: #incl #includ ude< e
CHAPTER – 13 ADVANCE CLASSES TEMPLATES Template is an advance feature in C++ that allows a single function or class to handle more than one data types. Generic Function: - There may be times when we duplicate a function just because we wanted it to support parameters of a different data type. For example, the following function compare(), compares two values of type int and returns the larger value: int compare (int a, int b) else { if (a>b) return b; return a; } If the two functi functions ons appear appear in the same same progra program, m, we must search search for a differe different nt name name for each of the functio functions. ns. Such complications are reduced by usages of templates of templates.. Thus, using templates, we can create generic functions. A Generic function is a function that could be used to work on different argument type.
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++ Generic Class: - Templates allow us to define generic classes. A generic class is a class that can be used with any data type. Parameterized templates give us the ability to create a general class, and pass data-type as parameter to that class, in order to build specific instances. Template Class: - Template is the latest features of c++. Template enables us to define generic function & generic class and provide facilities for generic programming. In generic programming parameters are generic means that parameters can be used for any data types. Program to demo. class templates template
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++ void print (T a) Float y = 10.56; { cout<<”all data types\n”; } Print(x); //function called with int data type void print int(float a) //o //overriding template fun function Print (y (y); //function ca called wi with fl float da data ty type { cout<<”float data type\n”; } Print (“Hello”); (“Hello”); //function //function called called with with string string data type Void main() } { int x = 10; Containers and Nested Class: - A container class is a class that operates on a collection of zero or more objects of a particular type. The use of template facility in defining container classes, will allow us to define a single class that can work for all data types. For example, we can define an object of container class Vector
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++ (v)
Initia Initializ lizee a stri string ng with with repeat repeated ed sequ sequenc encee of char charact acters ers.. string s1(6,’A’); Overloaded operator :--> (i) The As Assignment op operator(=) ------Lopies the string on the right side into the string on } the left side of the operator =. else Example--> string s1,s2; { s2=”ABC” -----s1=s2 } (ii) Comparison operator(<, (<,<=,>, ,>,>=) >=) (iii (iii)) Addi Additi tion on oper operat ator or(+ (+)) for for conc concat aten enat atio ion n Example--> string s1,s2; Example--> string s 1,s2,s3; s1=”ABC”; s1=”XYZ”; s2=”KBC”; s2=”PVT Ltd”; if(s1 member functions:(i) (i) bool bool emp empty ty() () :-:--> > This This mem membe berr func functio tion n retu return rnss true true if if the the siz sizee of list list is zero zero.. (ii) (ii) void void pop pop_f _fro ront( nt()) :--> :--> This This mem membe berr func functi tion on is is used used to to dele delete te the the fro front nt ele eleme ment nt.. (iii) (iii) void void push_f push_fron ront(e t(elem lement ent)) :--> :--> This This membe memberr functi function on is used used to add add the the eleme element nt in fron front. t. (iv) (iv) void void push push_re _rear(e ar(elem lement ent)) :--> :--> This member member functi function on adds adds the the elemen elementt at at rear rear.. (v) void void remo remove( ve(ele element ment)) :--> :--> This This memb member er functi function on remo removes ves all occurre occurrence ncess of of elem element ents. s. (vi) (vi) void void reve revers rse( e()) :--> :--> This This memb member er func functi tion on reve revers rsee the the lis list. t. (vii) (vii) void void sort() sort() :--> :--> This This membe memberr functi function on arran arranges ges the the elemen elements ts in the the ascen ascendin ding g order. order. Stack class --> #include
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++ New operator New operator is used to create exactly needed memory space at runtime for specified type. In c this operation is performed by a function namely malloc(). When our program is compiled it is broken into four parts. i.e. program code ,global data, stack and heap(free memory area). Example- int *p=new int; *p=5; Delete operator It is mainly used to releases the memory area. i.e. allocated by new operator. It is just like free() function of c. Example- delete p; Int *p= new int; *p=5; Delete p;
NOTES BY –BALJEET SINGH SINWAR
28