This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA
>k>>b; int p, q; } public: void c :: put4() void get3(); void put3(); { cout<<”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. Compile time polymorphism: - The overloaded member functions are “selected for invoking” 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 polymorphism: - In run time polymorphism, function is blind with their 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
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 posses specialized input and output stream behaviour, respectively. The istream class contain such functions as get(), getline() and read() while the stream class ontain such functions as put() and write(). • iostream class: - This is derived from both the istream and the ostream 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) – set field width for 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 tryblock. 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”; cin rel="nofollow">>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 class we need to place the statement: #include<string> Constructors String() It creates an empty class. Syntax: string s1; String s2(“kanak”) Initialize the string with a character array. String s1(s2) Initialize a string (say s1) from another string (say s2) using the statement String s1(6, ‘m’) Initialize a string as a repeated sequence of characters using the statement Function
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++ Assign() To reset a string’s values based on a substring of another string. Syntax: s1.assign(s2,1,2); Insert() To insert a string inside another. Syntax: s1.insert(2, “vinod”); Resize() To change the size of string. Syntax: s1.resize(20); Length() To determine the current length of string. Syntax: int 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 object of any data type. In order to use this class we need to place the statement: #include<stack>; Program to demo: #include<stack> #include
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 functions appear in the same program, we must search for a different name for each of the functions. Such complications are reduced by usages 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(float a) //overriding template function Print (y); //function called with float data type { cout<<”float data type\n”; } Print (“Hello”); //function called with 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)
Initialize a string with repeated sequence of characters. string s1(6,’A’); Overloaded operator :--> (i) The Assignment 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) Addition operator(+) for concatenation Example--> string s1,s2; Example--> string s1,s2,s3; s1=”ABC”; s1=”XYZ”; s2=”KBC”; s2=”PVT Ltd”; if(s1<s2) s3=s1+s2; { Member Function (i) Assign()- This member function is used to reset the string as: string s1; string s2(“ABCDEF”); s1.assign(s2,1,2); (ii) Insert()- Insert member function is used to insert set of characters in the string. string s1; s1.insert(2,”forest”); (iii) resize()- This member function is used to change the size of the string. string s1; s1.resize(5); (iv) Length()- It is used to calculate current length of the string. string s1(“KBC”); int l= s1.length(); List class--> #include<list> member functions:(i) bool empty() :--> This member function returns true if the size of list is zero. (ii) void pop_front() :--> This member function is used to delete the front element. (iii) void push_front(element) :--> This member function is used to add the element in front. (iv) void push_rear(element) :--> This member function adds the element at rear. (v) void remove(element) :--> This member function removes all occurrences of elements. (vi) void reverse() :--> This member function reverse the list. (vii) void sort() :--> This member function arranges the elements in the ascending order. Stack class --> #include<stack> member functions:(i) bool empty() :--> returns true if stack is empty. (ii) void pop() :--> removes the item from top of the stack. (iii) void push(element) :--> adds the item at the top of the stack. (iv) int size() :--> returns total number of element in a stack. Pointer --> Pointer is a special variable that can hold the address of another variable of same type. Pointer is associated with address. Using pointer, several features of c and c++ become easy/efficient to handle. Pointer provides another ways to work with a variable or function. We have to handle a variable with pointer then we must have to assign its base address to pointer. Variable- Variable is the popular element of programming language which is used to stored related types of data. Declaration of pointer :while(i<6) Datatype *pointer variable; { cout<<*ptr; Example ptr++; int *ptr, a; i++; a=15; } ptr=&a; String--> best example of Array(character) cout<<*ptr; *If we have to work with string ,then we use character array Array handling through pointer :to hold and manipulate the string. int s[6] ={1,3,5,7,2,4}; Example- char *string 1=”How many bytes are allocated for int*ptr,1; short int”; ptr=&s[0]; cout<<string1; i=0; cout<<string1[0]; Memory management using new and delete operators
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