Sie sind auf Seite 1von 52

VELAMMAL INSTITUTE OF TECHNOLOGY PANCHETTI DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING SUBJECT NOTES SUB.CODE: CS2203 SUB.

NAME: OBJECT ORIENTED PROGRAMMING UNIT I Object oriented programming concepts objects classes methods and messages abstraction and encapsulation inheritance abstract classes polymorphism. Introduction to C++ classes access specifiers function and data members default arguments function overloading friend functions const and volatile functions - static members Objects pointers and objects constant objects nested classes local classes Session No Topics to be covered Object oriented programming concepts Objects, Classes, Methods and Messages, Encapsulation and Data Abstraction inheritance, polymorphism, abstract classes Classes access specifiers Function and Data Members ,Default arguments, Function overloading Friend functions Static members Const and volatile functions, static functions Objects pointers and objects Nested classes Local classes Text Book Page No. 1(p 4-15) 2( p 5,16-18) 1(p -50,53-58) 2(p 142) 1(p 95-98,101-104) 2(p 68) 1(p-119-122) 1(p 127-134) 2(p 217) 1p(66-75,127-134) 2(p 150) 1(p135-139) 1( p79-81) 1(p 82-87)

2 3 4 5 6 7 8 9

REFER TEXT BOOK FOR MORE DETAILS

OBJECT ORIENTED PROGRAMMING CONCEPTS Objects: Objects are the basic run-time entities in an object oriented programming. They may represent a person, a place, a bank account or any item that the program has to handle. They may represent user-defined data such as vectors, time and lists. Programming problem is analyzed in terms of objects and the nature of communication between them. Objects are the instances of the classes. Objects Classes Data Abstraction Data Encapsulation Inheritance Polymorphism Message Passing

Velammal Institute Of Technology

Page 1

When a program is executed, the objects interact by sending messages to another. Each object contains data and code to manipulate the data. Objects can interact without having to know the details of each others data or code. It is sufficient to know the type of message accepted, and the type of message accepted and the type of response returned by the objects. Figure Shows the representation of an object.

Classes: A class is a way to bind the data and its associated functions together. It allows the data to be hidden if necessary from external use. While defining a class, we are creating a new abstract data type that can be treated as a built-in data type. A class Specification has two parts: 1. Class declaration describes the type & scope of its members 2. Class function definitions describe how the class functions are implemented.

The keyword class specifies that what follows is an abstract data of type class_name. The body of the class is enclosed within braces and terminated by a semicolon. The class body contains the declaration of variables and functions. These functions and variables are collectively called class members. The keywords private and public are known as visibility labels and it specify which members are private which of them are public. These should followed by a colon. Private members can be accessed only within the class whereas public members can be accessed form outside the class. By default, the members of a class are private. If both the labels are missing, the members are private to the class. // Program to demonstrate on objects : #include<iostream> #include<string> Velammal Institute Of Technology Page 2

using namespace std; class student { public : int Rollno; char Name[20]; char Address[20]; void GetDetails() { cout<< Enter the roll number; cin>> Rollno; cout<< Enter the Name; cin>>Name; cout<<Enter the Address; cin>>Address; } void PrintDetails() { cout<<Roll Number is << Rollno<<\n; cout<<Name is << Name<<\n; cout<<Address is << Address<<\n; } }; void main( ) { student Student1; Student1.GetDetails(); 14 Student1.PrintDetails( ); } Data Abstraction: Abstraction represents the act of representing the essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost and functions to operate on these attributes. The attributes are called data members and functions are called member functions or methods. Abstraction is useful for the implementation purpose. Actually the end user need not worry about how the particular operation is implemented. They should be facilitated only with the operations and not with the implementation. For example, Applying break is an operation. It is enough for the person who drives the car to know how pressure he has to apply on the break pad rather than how the break system functions. The car mechanic will take care of the breaking system. Data Encapsulation The wrapping up of data and functions into a single unit is known as encapsulation. It is the most striking feature of the class. The data is not accessible to the outside world and only those functions which are wrapped in the class can access it. These functions provide interface between the objects data and the program. This insulation of the data from direct access by the program is called data hiding or information hiding. Inheritance: It is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchical classification. For example, the person son is a part of the class father which is again a part of the class grandfather.

Velammal Institute Of Technology

Page 3

This concept provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. This is possible by a deriving a new class from an existing one. The new class will have the combined features of both the classes.

Types Of Inheritance: Single inheritance Multiple inheritance Hierarchical inheritance Multiple inheritance

Polymorphism: Polymorphism is the ability to take more than one form. An operation may exhibit different behavior depends upon the types of data used in the operation. Example: Consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation. The process of making an operator to exhibit different behaviors in different instances is known as operator overloading. shapes Draw() Triangle object Box object circle object Draw (circle) Draw (box) Draw (Triangle) Polymorphism A single function name can be used to handle different types of tasks based on the number and types of arguments. This is known as function overloading. Dynamic Binding Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is known until the time of the call at run-time. It is associated with polymorphism and inheritance. Message Passing Velammal Institute Of Technology Page 4

The process of programming in OOP involves the following basic steps: Creating classes that define objects and their behavior Creating objects from class definitions Establishing communication among objects A message for an object is request for execution of a procedure and therefore will invoke a function (procedure) in the receiving object that generates the desired result. Message passing involves specifying the name of the object, the name of the function (message) and the information to be sent. E.g.: employee.salary(name); Object: employee Message: salary Information: name INTRODUCTION TO C++ C++ is an object oriented programming language. It was developed by Bjarne Strousturp at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980s. C++ is a superset of C. Every C++ program must have a main( ). Like C, the statements terminate with semicolons. File Extension: C++ programs have the file extension .CPP Comments: It introduces a new comment symbol // (double slash). This is basically single line comment. The C comment symbols are still valid in C++. E.g. // Welcome to PIT - C++ style /* Welcome to PIT */ - C style The iostream File: #include <iostream.h> The header file iostream.h should be included at the beginning of all the programs that use input/output statements. Output Operator: cout << Hello World; The identifier cout (pronounced as C Out) is a predefined object that represents the standard output stream (screen). The operator << is called the insertion or put to operator. Input Operator: cin >> variable; The identifier cin (pronounced C in) is a predefined object in C++ that corresponds to the standard input stream (keyboard). The operator >> is known as extraction or get from operator. Cascading of I/O Operators: The statement cout << Sum = << sum <<\n; first sends the string Sum = to cout and then sends the value of sum. Finally, it sends the newline character so that the next output will be in the new line. Similarly the input operator can be cascaded as follows: cin >> num1 >> num2;

Velammal Institute Of Technology

Page 5

The values are assigned from left to right. That is if we type 27 and 13 then 27 will be assigned to num1 and 13 will be assigned to num2. Keywords: C++ has its own keywords in addition to the keywords in C. Some of them are catch class delete friend inline Identifiers: They refer to the name of the variables, functions, arrays, classes etc., created by the programmer. The rules for forming the variables are Only alphabetic characters, digits and underscores are permitted The name cannot start with the digit Uppercase and lowercase letters are distinct A declared keyword cannot be used as a variable name C++ allows the declaration of a variable anywhere in the scope. It makes the program easier to write and reduces the errors also makes the program easier to understand because the variables are declared in the context their use. Constants refer to the fixed values that do no change during the execution of a program. DATA TYPES: What are different data types supported by C++? (April/May 2007) User defined type structure union class enumeration Derived Type: Array Function Pointer Reference new operator private protected public template this throw try virtual

Built in type Integral type int char void Floating type float double User Defined Data Types: Structure: Structure is a heterogeneous data structure which can store data elements of mixed data types. Syntax: Velammal Institute Of Technology Page 6

struct tagname { elements of structures; }; Example: struct emp { int roll; char name[40]; }; emp e,e1; In the above code a structure named emp is created with the following elements namely rollno of integer data type name of character array type. Then two structure variables are created namely e,e1. Using the structure variables e and e1 the members (elements) of the structure can be accessed. Example e.roll=10; strcpy( e.name,ADAM); In structures all the elements of the structure are public by default. Scope Resolution Operator: What is the use of the scope resolution operator : : in C++? (Nov/Dec2007) Suppose there are two variables with the same name, one which is defined globally another is declared locally inside a function. If we attempt to access the variable a, we always access the local variable as the rule says, the local variable gets more priority over global variable. C++ provides a way to access the global variable using scope resolution operator. This scope resolution operator is used to define the function definition outside the class. Example: #include<iostream.h> int a = 27; void main() { int a = 13; cout << \nLocal value = << a << Global Value = << ::a ; ::a = 30; cout << \nLocal value = << a << Global Value = << ::a ; } Output: Local value = 13 Global Value = 27 Local value = 13 Global Value = 30 CLASSES A class is a way to bind the data and its associated functions together. It allows the data to be hidden, if necessary, from external use. When defining a class we are creating a new abstract data type that can be treated like any other built-in data type. Generally, a class specification has two parts: Class declaration Velammal Institute Of Technology Page 7

Class function definitions The class declaration describes the type and scope of its members. The class function definitions describe how the class functions are implemented. The general form of class declaration is Class class_name { private: variable declarations; function declarations; public: variable declarations; function declarations; }; Once you create a class type, you can declare one or more objects of that class type. For example: class X { /* define class members here */ }; int main() { X xobject1; // create an object of class type X X xobject2; // create another object of class type X } ACCESS SPECIFIERS Access specifiers are used to access the data members and member functions of the class. There are three types of access specifiers : private public protected private: the attributes that provide services (access) only to member functions are kept to be private.private is the default access mode for class members. public : the attributes that provide services (access) to outsiders are to be kept as public. protected : a member declared as protected is accessible by the member functions within its class and class immediately derived from it. It cannot be accessed by functions outside these two classes (base and derived). When a protected member function is inherited in public mode, it becomes protected in the derived class too and therefore is accessible by the member functions of the derived class. It is also ready for further inheritance. A protected member, inherited in the private mode derivation, becomes private in the derived class. Although it is available to the member functions of the derived class, it is not available for further inheritance. class alpha { private: // optional . // visible to member functions . // within its class protected: . // visible to member functions . // of its own and derived class public: . // visible to all functions . // in the program }

Velammal Institute Of Technology

Page 8

FUNCTION AND DATA MEMBERS The variables declared inside the class are known as data members and the functions as member functions. Only the member functions can have access to the private data and private functions. But the public members can be accessed from outside the class. Example: class item { int num; // variables declarations private by default float cost; public: void getdata(int, float); // function declaration using prototype void putdata(); }; Explanation: item class name, which is used to declare instances of that class type. It contains two data members and two function members. The data members are private by default and function members are public by declaration. getdata() Assign values to the variables num and cost putdata() Display the values of the variables Only the above functions can access the data members. Usually the data members are declared private, the function members are declared public. Creating Objects: Defining a class will not create any object as specifying just int will not create any variable. Once a class has been declared we can create variable of that type by using the class name. For example: item x; - creates a variable of x of type item. In C++, the class variables are known as objects. More than one object can be created using the statement as follows: item x,y,z; Accessing Class Members: The private data of a class can be accessed only by its member functions. Hence main() cannot access the private data of a class. The syntax for calling the member function is object-name.function-name(actual-arguments); With respect to the above example, x.getdata(27,65.5); It assigns the value 27 to num and 65.5 to cost. Similarly, x.putdata(); will display the values of num and cost. Velammal Institute Of Technology Page 9

Remember a member function can be invoked only by using an object. Defining Member Functions: Member functions can be defined in two ways: 1. Outside the class definition 2. Inside the class definition Outside the class definition: The general form of the definition is return-type class-name :: function-name(argument declaration) { function body } An important difference between a member function and a normal function is that a member function incorporates a membership identity label in the header. This label tells the compiler which class the function belongs to. The class-name :: tells the function function-name belongs to the class-name Example: void item :: getdata(int a,float b) { num = a; cost = b; } void item ::putdata() { cout << Num = << num <<\nCost = <<cost; } Characteristics: Several different classes can use the same function name. The membership label will resolve their scope. Member function can access the private data while a non-member function cannot. A member function can call another member function directly, without using dot operator. Default arguments A function can be called without specifying all its arguments. This wont work on just any function: The function declaration must provide default values for those arguments that are not specified. // Program to demonstrate default arguments #include<iostream.h> void repchar(char = *, int = 45); // declaration with default arguments int main( ) { repchar( ); // prints 45 asterisks repchar(=); // prints 45 equal signs repchar(+,30); // prints 30 plus signs return 0; } void repchar(char ch, int n) { for(int j=0;j<n;j++) // loops n times cout<< ch; // prints ch cout<<endl; }

Velammal Institute Of Technology

Page 10

In this program the function repchar( ) takes two arguments. It is called three times from main( ). The first time it is called with no arguments, the second time with one, and the third time with two. Why do the first two calls work? Because the called function provides default arguments, which will be used if the calling program doesnt supply them. Function Overloading: A single function name can be used to handle different types of tasks based on the number and types of arguments. This is known as function overloading. Using the concept of function overloading; we can design a family of functions with one function name but with different argument lists. The function would perform different operations depending on the argument list in the function call. The correct function to be invoked is determined by checking the number and type of the arguments but not on the function type. For example, an overloaded add( ) function handles different types of data as shown below: // Declarations int add(int a, int b); // prototype 1 int add(int a, int b, int c); // prototype 2 double add(double x, double y); // prototype 3 double add(int p, double q); // prototype 4 double add(double p, double q); // prototype 5 // Function calls cout << add(5,10); // uses prototype 1 cout << add(15,10.0); // uses prototype 4 cout << add(12.5,7.5); // uses prototype 3 cout << add(5,10,15); // uses prototype 2 cout << add(0.75,5); // uses prototype 5 A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. // Program to demonstrate function overloading #include<iostream> //Declarations (prototypes) int volume(int); double volume(double, int); long volume(long, int, int); int main( ) { cout << volume(10) << \n; cout << volume(2.5, 8) << \n; cout << volume(100L, 75, 15) << \n; return 0; } // Function definitions int volume (int s) // cube { return(s * s * s); } double volume (double r, int h) // cylinder { return(3.14 * r * r * h); } double volume (long l, int b, int h) // rectangular box { return(l * b * h); } The output of the above program would be : Velammal Institute Of Technology Page 11

1000 157.26 112500 Friend Functions In OOP environment, the private members cannot be accessed from outside the class. That is, a non-member function cannot have an access to the private data of a class. To allow a function (non-member) to have access to the private data of a class, the function has to be made friendly to that class. To make an outside function friendly to a class, we have to simply declare this function as a friend of the class as shown below : The function declaration should be preceded by the keyword friend. The function is defined elsewhere in the program like a normal C++ function. The function definition does not use either the keyword friend or the scope resolution operator : :. The functions that are declared with the keyword friend are known as friend functions. A friend function can be declared as a friend in any number of classes. A friend function, although not a member function, has full access rights to the private members of the class. Characteristics (certain special characteristics) of Friend functions: It is not in the scope of the class to which it has been declared as friend. Since it is not in the scope of the class, it cannot be called using the object of that class. It can be invoked like a normal function without the help of any object. Unlike member functions, it cannot access the member names directly and has to use an object name and dot membership operator with each member access.(e.g. A . x). It can be declared either in the public or private part of a class without affecting its meaning. Usually, it has the objects as arguments. // program to demonstrates the use of a friend function #include<iostream> using namespace std; class sample { int a; int b; public: void setvalue( ) { a = 25; b = 40; } friend float mean (sample s); // declaration }; float mean (sample s) { return float(s.a + s.b) / 2.0 ; } int main( ) { sample X; // object X X.setvalue( ); cout << Mean Value = << mean(X) << \n; return 0; } The output of the above program would be : Mean Value = 32.5

Velammal Institute Of Technology

Page 12

The friend function accesses the class variables a and b by using the dot operator and the object passed to it. The function calls mean(X) passes the object X by value to the friend function. Member functions of one class can be friend functions of another class. In such cases, they are defined using the scope resolution operator as shown below: class X { . . int fun1( ); // member function of X . }; class Y { . . 36 friend int X : : fun1( ); . }; The function fun1 ( ) is a member of class X and a friend of class Y. We can also declare all the member functions of one class as the friend functions of another class. In such cases, the class is called a friend class. This can be specified as follows: class Z { . friend class X; // all member functions of X are friends to Z }; program with a function friendly to two classes #include<iostream> using namespace std; class ABC ; // forward declaration class XYZ { int x; public : void setvalue(int i) { x = i ;} friend void max(XYZ, ABC); }; class ABC { int a; public : void setvalue(int i) { a = i ;} friend void max(XYZ, ABC); }; // definition of friend function void max(XYZ m, ABC n) { if(m.x >= n.a) cout << m.x; else cout << n.a; 37 } Velammal Institute Of Technology Page 13

int main( ) { ABC abc; abc.setvalue(10); XYZ xyz; xyz.setvalue(20); max(xyz, abc); return 0; } The output of the above program would be : 20 Note : The function max( ) has arguments from both XYZ and ABC. When the functions max( ) is declared as a friend in XYZ for the first time, the compiler will not acknowledge the presence of ABC unless its name is declared in the beginning as class ABC; This is known as forward declaration. Const and Volatile functions: If a member function does not alter any data in the class, then we may declare it as a const member function. The compiler will generate an error message if such functions try to alter the data value. The qualifier const is appended to the function prototypes (in both declaration and definition). The syntax of declaring a const function is given below <return type> <function name>(argument1,argument2,) const ; Example: void mul(int, int) const ; double get balance( ) const ; The syntax of defining a const function is given below : <return type> <function name>(argument1,argument2,) const { <The function body> } Example : void PrintDetails( ) const { cout << Roll Number is : << RollNumber << \n; cout << Name is : << Name << \n; cout << Address is : << Address << \n; } Volatile functions: A member function can be declared as volatile if it is invoked by a volatile object. A volatile objects value can be changed by external parameters which are not under the control of the program For example, an object taking an input from a Network Interface Card does not take input from our program. As and when the hardware interrupts, the values related to it change without our programs knowledge. A sample definition of volatile function and volatile object is shown below: class NICClass { public: void CheckValueForNIC volatile // a volatile function definitions { // function body } . }; volatile NICClass NICObject; // a volatile object definition Velammal Institute Of Technology Page 14

Constant Objects: Const objects are objects that are not modifiable. C++ provides safeguarding against accidental modification by not allowing access of the object to a normal member function. Const object, obviously, is not allowed to do operations which modify the object. Only functions that are defined as const can be accessed by const objects. Even public variables of the object are not modifiable. Const member functions are functions that make sure that an object is not modified. A normal function cannot be invoked by const objects. Thus the object maintains its integrity. When we do not want any accidental change in the objects properties, we should define the object as a const object. //ConstObj.cpp #include<iostream> #include<string> using namespace std; class student { public: int RollNumber; string Name; string Address; void PrintDetails( ) const /* this function is now constant, it can now be accessed by const bject of class student*/ { cout<<RollNumber is<<RollNumber<<\n; cout<<Name is<<Name<<\n; cout<<Address is<<Address<<\n; } }; void main() { student Student1; Student1.RollNumber=1; Student1.Address=NewDelhi; Student1.Name=Rahul; Student1.PrintDetails(); Student Student2= Student1; Student Student3; Student3= Student1; Student2.PrientDetails(); Student3.PrientDetails(); const student OtherStudent= Student1; //Following is erroneous if PrintDetails( )is not const OtherStudent.PrintDetails(); /* Following line wontt compile because it tries to modify a constant object*/ OtherStudent.RollNumber=5; /*Following will work*/ cout<<OtherStudent.RollNumebr; Static Members Static variables are normally used to maintain common to the entire class they are initialized only once Features: It is initialized to zero when the first object is created. No other initialization is permitted Velammal Institute Of Technology Page 15

Only one copy of member is created for entire class and is shared by all the objects It is visible within the class, but lifetime is the entire class It is stored separately rather than objects Accessing data members Two ways Classname::datamember name Classname.datamember name Static member function A member function that is declared as static has the following properties A static function can have access to only other static members declared in the same class They do not possess this pointer They cannot be virtual They cannot be declared either const or volatile Accessing member function Classname::function_name(arguments) Program #include<iostream.h> #include<conio.h> class staticmember { int a; static int count,cnt; public: void set() { a=++count; cnt++; } void show() { cout<<"\n"; cout<<"Object Number:"<<a<<"\n"; } static void showcount() { cout<<"Static count value:"<<count<<"\n"; cout<<"Static cnt value:"<<cnt<<"\n"; } }; int staticmember::count; int staticmember::cnt = 100; void main() { staticmember s1,s2,s3; clrscr(); s1.set(); s1.show(); cout<<endl; s2.set(); staticmember::showcount(); Velammal Institute Of Technology Page 16

s2.show(); cout<<endl; s3.set(); staticmember::showcount(); s3.show(); cout<<endl; getch(); } Output: Object Number:1 Static count value:2 Static cnt value:102 Object Number:2 Static count value:3 Static cnt value:103 Object Number:3 Pointer to Objects and Pointer to Members Professional programs using C or C++ are almost impossible to use without pointers. In C++, pointers can also have an address for an object. They are known as pointers to objects. The difference is that pointers themselves are variables that contain addresses. In that sense, there is no difference. A pointer to an object contains an address of that object. Pointer increment will increment the address by the size of the object. The size of the object is determined by the size of all of its non-static data elements. We have already seen that the functions and static data members are not stored with the object and do not count for the size of an object. (It is a little different when the class is an inherited one. Inherited classes are complex. Consider the following example: #include <iostream> #include <string> using namespace std; class student { public: int RollNumber; string Name; string Address; void PrintDetails() { cout << Roll Number is << RollNumber << cout << Name is << Name << cout << Address is << Address << \n; } }; void main() { student *studentpointer; Studentpointer = new student; // we can also write student *Studentpointer = new student; //Section 1 (*Studentpointer) .RollNumber = 1; (*Studentpointer) .Name = Robin Singh; Velammal Institute Of Technology Page 17

(*Studentpojnter) .Address= New Delhi ; (*Studentpointer> .PrintDetails(); //Section 2 StudentPointer -> RoilNumber = 1; StudentPointer -> Name =Robin Singh; StudentPointer -> Address= New Delhi; StudentPointer -> PrintDetails(); //Section 3 int student * Rollpoint = & student: :RollNumber; /*It defines a pointer Rollpoint to point to roll number. Note it is not int *Rollpoint = &RollNumber */ student NewStudent; NewStudent.*Rollpoint = 2; student * NewstudPoint = &NewStudent; cout << \n Now the Roll No is ; cout << NewStudPoint -> RollNumber; NewStudPoint >RollPoint = 3; cout << \n Now the Roll No is ; cout << NewStudPoint RoilPoint; cout << NewStudent.*RollPoint; This program gives us the following output: Roll Number is 1 Name is Robin Singh Address is New Delhi Roll Number is 1 Name is Robin Singh Address is New Delhi Now the Roll No is 2 Now the Roll No is 3 Now the Roll No is 3Press any key to continue Inline functions An inline function is a function that is expanded in line when it is invoked. That is, the complier replaces the function call with the corresponding function code. The inline function is defined as follows: Syntax : inline function header { function body } Example : inline int cube(int a) { return (a*a*a); } // Program to demonstrate inline functions : #include<iostream.h> inline float mul(float x, float y) { return (x*y); } inline float div(double p, double q) { return( p / q ) } Velammal Institute Of Technology Page 18

int main() { float a=12.35; float b=9.32; cout<< mul(a,b); cout<<div(a,b); return 0; } The inline functions are not suitable where the function definition (body) is very lengthy and invoked very often in the program Nested Classes It is possible to define a class inside another class. Look at the following example: #include <iostream> using namespace std class Outside { private: class Inside { public: int Insidelnt; void Setlnsidelnt(int Templnside) { Insidelnt =Templnside; } }; // This ends the inner class definition public: int Outsidelnt; void Uselnside() { Inside in; In.setinside(3); } };// this ends the outer class definition int main() { Outside Out; Out.useinside(); } We have two classes. Outside class is a nesting class and contains the entire body of the inside class. The inside class, which is defined inside the outside class, is also known as the nested class. The definition of the class inside does not contain anything new. If it is defined outside, the definition would not be different.

Local Classes: When a class is defined inside functions it is called as local class. // Program to demonstrate Local classes : #include<iostream> #include<string> using namespace std; void main( ) { int RollNo = 3 ; Velammal Institute Of Technology Page 19

void TestStudent(int); //prototype of TestStudent function ; class student is //not known here TestStudent (RollNo); } void TestStudent(int Roll) { int TestValue = 100 ; static int StaticTestValue = 200 ; class student // Now this class is a local class! { // only in TestStudent function the class is available public : int RollNumber; string Name; string Address; void PrintDetails( ) // now this function cannot be defined // outside this class { cout << TestValue // this is not valid since TestValue and cout<<::StaticTestValue;//StaticTestValue are private variable //of the class cout << Roll Number is : <<RollNumber<<\n; cout << Name is : <<Name<<\n; cout << Address is : <<Address<<\n; } }; student Student1; Student1.RollNumber = Roll; Student1.Name = Ragul; Student1.Address = New Delhi; Student1.PrintDetails( ); } Following are some restrictions on the use of local classes: They cannot use auto local variables of the container function. (Eg. TestValue) They can access static local variables or extern variables(globally defined) of the container function(Eg.StaticTestValue ) They cannot contain static member themselves They cannot define their function outside the class boundaries.Here the PrintDetails( ) must be defined inside the class. Their private variables are not available to container function unless declared as friend.

Velammal Institute Of Technology

Page 20

UNIT II Constructors default constructor Parameterized constructors Constructor with dynamic allocation copy constructor destructors operator overloading overloading through friend functions overloading the assignment operator type conversion explicit constructor Session No 10 11 12 13 Text Book Page No. 1(p170-178,183184) 2(p 168-169) 1(p 199-216) 2(174,199) 1(p193-198) 1 (p 231-240) 1 (p 241-245) 2(p 221-223) 1(p 246-248) 1 (p 251-255) 2(p 225) 1(p 269-279) 1(p 181-183) REFER TEXT BOOK FOR MORE DETAILS

Topics to be covered Constructors Default constructor Parameterized constructors Copy constructor Destructors Constructor with dynamic allocation Operator overloading Operator overloading through member functions. Operator overloading Unary operator overloading Binary operator overloading Overloading through friend functions Overloading the assignment operator Type conversion Explicit constructor

14 15 16 17 18

Constructors Constructor is a special member function whose task is to initialize the objects of its class 1. 2. 3. A constructor need not be called explicitly, but it is automatically called when the object is defined. Constructor provides initial values for the data members of the object. Constructor function has the same name as the class itself.

Rules for Defining A Constructor 1. 2. Constructor must have the same name as the class. If we need more than one constructor we should have single and overload it with different set of arguments. Page 21

Velammal Institute Of Technology

3.

Constructor should not have return type though it returns the object of the class it belongs to after constructing it. It should not have a return statement in the body of the function. Address of constructor cannot be obtained. We can define constructor as private but itll be disable from defining objects. It should be defined in the public section of the class.

4. 5. 6. 7.

Need For Object Initialization 1. When an object is declared, the data members should be initialized to specific values i.e.int variable to zero, pointer variable to NULL Dynamic memory allocation may be required when object is defined. E.g. item purchased by an individual may vary a lot; it is enough to provide memory for those items alone. Constructor help in both defining the object and giving them some specific value. Void memory is given to the constructor function. When inheritance in effect, if the base class has a constructor, derived class also has to have one constructor of its own.

2.

3. 4. 5.

Types Of Constructors Default Constructor- No Argument Constructor Constructor With One Argument Parameterized Constructor Copy Constructor Constructor With Dynamic Memory Allocation Explicit Constructor Default Constructor (or) No Argument Constructor Constructor function of a class can have any no of arguments, if the constructor function has no arguments; it is called no argument constructor or default constructor. If a programmer fails to create a constructor for a class, the compiler will create a constructor by default in the name of the class without having any argument at the time of compilation and provide initial values to data members. The default constructor is created whenever the object of the class is created. Program: #include<iostream> #include<conio> using namespace std; class student { int m1,m2; public: student() // no argument constructor { Velammal Institute Of Technology Page 22

m1=0; m2=0; } }; void main() { student s; } When the object s is declared, it in turn calls the no argument constructor and initializes m1 and m2 to 0. One Argument Constructor If the constructor has one argument, then it is called one argument constructor. A constructor with one argument is special because whenever we define a constructor containing a single argument. The compiler automatically defines a conversion operator for converting between the argument type and object type. The type conversion takes place implicitly without having any conversion operation. Program #include<iostream> #include<conio> using namespace std; class student { int mark; public: student() // no argument constructor { } student(int x) // one argument constructor { mark=x; } }; void main() { student s1; s1(1140); } PARAMETERIZED CONSTRUCTOR When a constructor contains single or multiple arguments, it is called parameterized constructor. This constructor is useful when we need constructor for creating object with required values initialized. With parameterized constructor, we pass value to them unlike default constructor. To invoke parameterized, we need to pass initial values as arguments to constructor function when an object is declared. e.g. #include<iostream> #include<conio> using namespace std; class student { int m1,m2; public: student() { } student(int x,int y) // parameterized constructor Velammal Institute Of Technology Page 23

{ m1=x; m2=y; } void display() { cout<<m1<<m2; } }; void main() { clrscr(); student s1; s1(3,4); //implicit Conversion 3 and 4 is converted to student object then it is assigned s1.display(); getch(); } O/P: 3 4 Copy Constructor Copy constructor is used to declare and initialize an object from another object. It takes reference to an object of the same class as argument. Example Calling the Copy constructor if the class name is integer; integer i1; integer i2(i1); integer i2=i1; Syntax classname(classname &object) { } Constructor function takes objects of the same class as argument. Example: #include<iostream> #include<conio> using namespace std; class integer { int m; public: integer() // no argument constructor { m=0; } integer(int a) // parameterized constructor { m=a; } integer(integer &i) Velammal Institute Of Technology Page 24

{ m=i.m; } void show() { cout<<m=<<m; } }; void main() { integer i1; i1.show(); integer i2(4); i2.show(); integer i3(i2); i3.show; } O/P: m=0 m=4 m=4

Constructor With Dynamic Memory Allocation Constructor can use new to allocate memory for objects at the time of creation. Such constructors are common when the objects can be of varied size and size is available only at runtime Example: #include<iostream> #include<conio> #include<string> using namespace std; class item { int item_no; string item_name; public: item() { item_no=0; item_name= ; } item(item temp_item_no, string temp_item_name) { item_no=temp_item_no; item_name=temp_item_name; } void showdetails() { cout<<\n\nItem number is<<item_no; cout<<\n\nItem name is<<item_name; } class customer { int cno; string cname; string caddress; item *item_interested; int total_items; public: Velammal Institute Of Technology Page 25

customer() { total_items=0; item_interested=0; } customer(int n,string n,string add,item *i,int tot) { cno=n; cname=n; caddress=add; item_interested=new item[tot]; for(int n=0;n<tot;n++) { item_interested[n]=i[n]; } total_items=tot; } void show() { cout<<cno; cout<<cname; cout<<caddress; cout<<\n<<cname<<is interested is \n; for(int j=0;j<total_items;j++) { item_interested[j].show(); } } }; void main() { customer steve; item itemarray[]={item(3,sandwiches), item(4,paperbags), item(5,toys), item(6,pen), item(2,eraser)}; steve=customer(2,stevewaugh,Australia,itemarray,5); steva.show(); customer flintoff(3,captain,England,itemarray+2,6); flintoff.show(); } Multiple Constructors (Or) Overloading Constructor Function and Constructor with default arguments Its is possible to have multiple constructors for a class. To overload any function, the function should have argument, since the constructor function takes arguments .it is possible to overload #include<iostream> #include<conio> class employee { int empno; char *emp_name, *address; public: employee() { empno=0; emp_name=NULL; address=NULL; } employee(int a) { Velammal Institute Of Technology Page 26

empno=a; emp_name= ; address= ; } employee(int a, char *b=sam,char *d= ) { empno=a; emp_name=b; address=d; } void main() { employee e1; employee e2(3,sam,Bangalore); employee e3(3); } Destructors A destructor destroys an object of its class type. Destructors are special functions and it is called when the object of a class goes out of scope. Destructors destroys the object which is most recently created first Rules For Defining A Destructor 1. 2. 3. 4. 5. A destructor should have the same name as the class name with a ~ sign prefixed. The destructor should be defined in the public section of the class. Destructor cannot be overloaded. A destructor should not have a return type. If a programmer fails to create a destructor for a class, the compiler will create a destructor by default in the name of the class. It deallocates memory for the data members created by the constructor.

6.

Syntax (or) General Form ~ Classname(); Example: #include<iostream.h> #include<conio.h> int i=10; class student { public: student() { cout<<Object created<<i; i++; } ~student() // destructor { cout<<\n\nObject destroyed<<i; i--; } }; void main() Velammal Institute Of Technology Page 27

{ student s1,s2,s3,s4; } o/p: 1011121313121110 Operator overloading: C++ will provide an additional task to an existing operator. The mechanism of redefining an existing operator to a user-defined datatype is called operator overloading. Example: (i) 2+2=4 (ii) 2.3+3.2=5.5 (iii) e1+e2 //addition of two objects Here the operation we use is addition operator to add two values. So depending on the input given, the operator will behave differently. If it is an integer value, it will add, if it is a float value, it will add.In C++ such operator functionality can be extended to objects also. Rules for operator overloading: 1. Only existing operator can be overloaded. 2. The meaning of the operator should not be changed. 3. The overloaded operator must have operand that is of user defined datatype. 4. They should not be overridden 5. Except function Call operator (),no other operator can have a default argument Operators that cannot be overloaded: size of operator dot operator for member access scope resolution (::) dereference operator(.*) # and ## tokens for macro preprocessors conditional operator(?) Operators that cannot be overloaded as friend: assignment operator = function call operator () array subscript operator [] class member access -> Operator Function Operator overloading is performed by adding special member functions to the class, which are known as operator functions. The operator function can be used as either member function or a friend function Operator function describes the action to be performed by the operator Syntax: Operator function as member function Return_type operator operator-symbol(arglist) { Function Body } Operator function as friend function Velammal Institute Of Technology Page 28

Friend Return_type operator operator-symbol(arglist) { Function Body } Types Of Operators: Unary Works on one operand Binary - Works on Two operand The following table shows how to use operator function for overloading the unary as well as binary operator Operator Function Operator Type Unary Binary Member Function No argument One argument Friend Function One reference object as argument Two reference objects as arguments

Calling operator function Operator Function Operator Type Unary Binary Member Function Operator-Symbol object; Object1 operator-symbol Object2; Friend Function Object1=Operator-Symbol (object2); Object1 operator-symbol Object2;

Overloading a unary operator Through Member Function: Operator having one single argument are called unary operator. When we overload these operators as member function. We need not pass any argument explicitly. Example program: #include<iostream.h> #include<conio.h> class unary { int a,b; public: unary() { } unary(int x,int y) { a=x; b=y; } void operator -() //operator function { a=-a; b=-b; } void print() { cout<<"a="<<a; Velammal Institute Of Technology Page 29

cout<<"b="<<b; } }; void main() { unary u1(1,2); -u1; u1.print(); unary u2(-5,7); -u2; u2.print(); } Overloading Unary increment and decrement operator through member function: Both increment and decrement operators are two version of C++, they are prefix and postfix version. They are differentiated by their position . if its before operand then it is called prefix version and after operand its is called postfix version #include<iostream.h> #include<conio.h> class unary { int a; public: unary() { } unary(int x) { a=x; } void operator ++() { a++; } void operator ++(int dummy) { a++; } void operator --() { a--; } void operator --(int dummy) { a--; } void print() { cout<<"a="<<a; } }; void main() { unary u1(3); u1++; // Calling Postfix increment function u1.print; Velammal Institute Of Technology Page 30

u1--; // Calling Postfix decrement function u1.print(); ++u1; // Calling prefix increment function u1.print; --u1; // Calling Prefix decrement function u1.print(); } Overloading through friend function Operator function can be defined as friend function. The only difference between a friend function and member function is that the friend function requires the arguments to be explicitly passed to the function and process them explicitly, friend function can be used either with unary or binary operator Overloading unary operator through friend function: The following program illustrate the concept of overloading an increment operator where the operation function used as friend function #include<iostream.h> #include<conio.h> class weight { private: int kg,gm; public: weight() { } weight(int k,int g) { kg=k; gm=g; } friend weight operator ++(weight&) friend weight operator --(weight&) }; weight operator ++(weight &w) { W=w.kg++; W=w.gm++; return w; } weight operator --(weight &k) { K=k.kg--; K=k.gm--; return k; } void main() { weight w1,w2,w3; w3=w1++; w3.print(); w3=w2--; w3.print(); } Overloading binary operator through friend function:

Velammal Institute Of Technology

Page 31

#include<iostream.h> #include<conio.h> class weight { private: int kg,gm; public: weight() { } weight(int k,int g) { kg=k; gm=g; } friend weight operator +(weight &w1,weight &w2) { weight temp; temp kg=w1.kg+w2.kg; temp gm=w1.gm+w2.gm; return temp; } friend weight operator -(weight &w1,weight &w2) { weight temp; temp kg=w1.kg-w2.kg; temp gm=w1.gm-g2.gm; return temp; } void temp() { weight w1(3,5),w2(4,6),w3; w3=w1+w2; w3.print (); } Overloading Assignment Operator By overloading the assignment operator, the source object can be copied to destination automatically. The following assignment statement Ob1=Ob2; will cause the compiler to copy the data from Ob2,member by member into Ob1. #include<iostream.h> #include<conio.h> Using namespace std class assignment { private: int x; public: assignment() {} assignment(int y) { x=y; } void operator=(assignment); Velammal Institute Of Technology Page 32

void print() { cout<<x:<<x; } }; Void assignment::operator =(Assignment as) { X=as.x; } void main() { assignment a1(10); assignment a2; a2=a1; a2.print(); } SAMPLE OUTPUT: x:10 In main(), first statement creates an object a1 and it calls the one argument constructor to initialize its data member.In the second statement object a2 is created which calls the no argument constructor to initialize 0 to its data member by default .In the third statement, the value of object a1 is assigned to object a2. So,it calls the operator function to copy the object a1s data member to object a2s data member. Type Conversion Type conversion takes place between the incompatible data types. There are three types of data conversions. They are: Conversion from Built-in data type to an object. Conversion from object to a Built-in data type. Conversion from one objects type to another object type. Any type conversion involving a class is defined either by a conversion constructor or by a conversion operator function. The constructor performs type conversion by converting any given type to the type of the current class. A conversion operator function performs conversion in the opposite direction, that is, it converts an object of the current class to another type. The general form of this function is, Syntax: operator type-name() { function body } A conversion operator function is a function that satisfies the following conditions It must be a member function It must not specify a return type It must not have any arguments Velammal Institute Of Technology Page 33

Conversion from Built-in data type to object Conversion from basic data type to object type can be done with the help of constructors. Constructor takes a single argument whose type is to be converted. The following program illustrates this concept #include<iostream> #include<conio> using namespace std; class Sample { int x; public: Sample() {} Sample(int a) { x=a; } void Print() {cout<<x;} }; void main() { Sample s1; s1=5; s1.Print(); } In main(), the statement s1=5; converts built-in data type int to the object s1 by invoking the conversion constructor: Sample(int a){ . } This constructor is invoked while creating objects of the class Sample using a single argument of type int. Conversion from object to a Built-in data type Using conversion operator function, conversion form object of a class to a built-in type can be done. The following program explain this concept. #include<iostream> #include<conio> using namespace std; class Sample { int x; public: Sample(int a) { x=a; } operator int() // conversion operator function { return x; } }; void main() { Sample s1(10); int a=s1; // calling conversion operator function cout<<a; } Velammal Institute Of Technology Page 34

In main(), the statement, int a=s1; converts the object s1 to built-in data type int by invoking the overloaded operator function. The above conversion operator function can also be invoked explicitly as follows: int a=(int)s1; or as int a=int(s1); The compiler invokes the appropriate conversion function. First, the compiler looks for an overloaded = operator. If does not find one, then it looks for a conversion operator function and invokes the same implicitly for data conversion. Conversion from one object to another object using conversion constructors We can convert from one type of object into another type of object using either constructors or conversion operator function. The following program explains how to convert from one object to another object of different classes using constructor function. #include<iostream> #include<conio> using namespace std; class Sample { private: int x; public: Sample1(int a) { x=a; } int GetA() { return x; } }; class Sample2 { private: int y; public: Sample2() {} Sample2(Sample1 s1) { y=s1.GetA(); } void Print(){cout<<y;} }; void main() { Sample1 s1(10); Sample2 s2; s2=s1; s2.Print(); }

// constructor used for conversion

// calling constructor function

In main(),s1 and s2 are objects of different classes,s1 is object of Sample1 class and s2 is object of Sample2 class. The statement, s2=s1; Velammal Institute Of Technology Page 35

converts the object s1 into s2 by invoking the constructor function. Conversion from one object to another object using conversion operator function The following program explains how to convert from one object to another object of different classes using conversion operator function. #include<iostream> #include<conio> using namespace std; class Sample { int x; public: One() {} One(int a) { x=a; } void Print() { cout<<x; } }; class Two { int y; public: Two(int b) { y=!y; } operator One() { return One(y); } }; void main() { One o1; Two t1(10); o1=t1; o1.Print(); }

// conversion operator function // return to one arg. constructor of class One

// calling the conversion operator function

In main(), the objects o1 and t1 are incompatible objects since the object o1 is created for class One and object t2 belongs to class Two. In general, it is possible to assign object of a class with object of another class, but the statement , o1=t1; Calls the conversion operator function to make this possible. Explicit Constructor A constructor that takes a single argument is, by default an implicit conversion operator that converts its argument to an object of its class, to avoid such implicit conversions, a constructor that takes one argument can be declared explicit Syntax:

Velammal Institute Of Technology

Page 36

Class Student { Public: Explicit student(char *temp) } Program

// disallow implicit conversion

#include<iostream> #include<conio> using namespace std; class student { int mark; public: student() // no argument constructor { } Explicit student(int x) // one argument constructor { mark=x; } }; void main() { student s1; s1(1140); //disallow implicit conversion student s1=student(300) // explicit calling constructor }

Velammal Institute Of Technology

Page 37

UNIT III Function and class templates - Exception handling try-catch-throw paradigm exception specification terminate and Unexpected functions Uncaught exception. Session No 19 20 21 22 23 24 25 26 27 Topics to be covered Function Templates, Function Templates with single arguments Function Templates with multiple arguments, Function Templates with 2 generic arguments, non generic parameters Template function specialization, Explicitly specializing a template function. Class template, Defining functions outside Class template Classes with multiple generic data types Friends of class templates. Exception handling try-catch-throw paradigm Exception specification Terminate and Unexpected functions Uncaught exception. Ref 1(p 285-295) 2(p 280-282) 1(p 296 302) 1(p 303-313) 1(p 315-327) 2(p 283-284) 1(p 328-334) 1(p 343-347,353358) 2(p 368) 1(p 358-365) 1(p 369-372) 1(p 373-376) REFER TEXT BOOK FOR MORE DETAILS

Function Templates And Class Templates Templates In C++: Template is a feature of c++ programming language that allows functions and class to operate on generic data type. It is a style of programming in which algorithm are returned in terms of to be specified later types, that are then instantiated when needed for specific types provided as parameters. Template allows a function or class to work on many different data types without being rewritten for each one. The benefit of object oriented programming is reusability of code which eliminates redundant coding. Important features of object oriented programming called templates makes this benefit stronger and provide flexibility. Template supports generic programming which allows developing a reusable software component such as functions and classes supporting different data types in a single framework. Two Types of templates, they are Function templates Class templates Function Templates

Velammal Institute Of Technology

Page 38

The template declared for functions are called function templates, function templates are generic functions which works for any data type that is passed to them, the data type is not specified while declaring the function. It performs appropriate operations depending on the data type we passed to them Syntax: template<typename T,> returntype functionname(argument list); { Function Body } Where Template is a keyword,typename T is a template data type Example: #include<iostream> #include<conio> using namespace std; template<class T> void GenericBubblesort(T tempgenericarray[]) { for(int i=0;i<5;i++) { for(int j=i+1;j<5;j++) { if(tempgenericarray[i]<tempgenericarray[j]) { int temp=tempgenericarray[i]; tempgenericarray[i]=tempgenericarray[j]; tempgenericarray[j]=temp; } } } } template<class T> void genericdisplay(T genericarray[]) { cout<<\n; for(int i=0;i<5;i++) { cout<<tempgenericarray[i]<<\t; } void main() { int array1[]={1,4,6,2,6}; GenericBubblesort(array1); genericdisplay(array1); char array2[]=sdfka; GenericBubblesort(array2); genericdisplay(array2); float array3[]={7.0,9.4,5.2,2.5,0.5}; GenericBubblesort(array3); genericdisplay(array3); } OUTPUT: 66421 skfda Velammal Institute Of Technology Page 39

9.4 7.0 5.2 2.5 0.5 Function template with multiple arguments It is possible to have templates with one or more arguments .one argument can be generic or normal. Example: #include<iostream> #include<conio> using namespace std; template<class T> void max(T x,T y) { if(x>y) cout<<x<<is bigger; else cout<<y<<is bigger; } void main() { int a=3,b=5; max(a,b); float f1=3.5,f2=9.5; max(f1,f2); char d=e,e=b; max(d,e); } CLASS TEMPLATES: Similar to function, class can also be declared as templates. Such classes are called as class templates. There are three differences between normal class and templatized class. The three differences are as follows: The class header class stack changes to: template<typename elementtype> class stack temp template<class T> precedes the class definition for the class to use element type as a generic datatype in the body of the class. The definition stack mystack changes to stack<int>mystack The int element type argument to push and return type of pop have been replaced here by element type. We can also have char stack and employee stack like the int stack. We have seen that the program will not have any change in the class definition. It is to be noted that it is possible to have automatic argument deduction in class templates because the compiler cannot deduce a type from the object declaration like stack mystack. It is not similar to a function call where we have arguments and deducing which may tell a compiler the datat type for the type. Example: #include<iostream> #include<conio> using namespace std; template<class T> class stack Velammal Institute Of Technology Page 40

{ private: int stackpointer; T stackarray[10]; public: stack() { stackpointer=0; void push(T value) { if(stackpointer==9) { cout<<Stack overflow! cant insert; } else { stackarray[stackarray]=value; stackpointer++; } } T pop() { if(stackpointer==0) cout<<Stack underflow,cannot pop; else { stackpointer--; return stackarray[stackpointer]; } } }; void main() { stack<int>mystack; mystack.push(1); mystack.push(2); cout<<mystack.pop()<<\n; cout<<mystack.pop()<<\n; stack<char>s; s.push(n); s.push(o); cout<<s.pop()<<\n; } Exception handling It refers to unexpected conditions in a program. Unexpected condition could be a fault, causing an error which in turn causes the program to fail. Exceptions are subsets of error. The basic idea is that error occurring in particular part of a program reported to another part of a program. Need for exception handling: Exceptional handling is needed in c++ because of all the inappropriate traditional solutions. Dividing the error handling For separating error reporting and error handling To solve the object destroy problem Page 41

Velammal Institute Of Technology

Components of Exception Handling mechanism To separate error reporting and error handling components of exceptional handling, It has three blocks: Try for indicating program area where the exception can be thrown Throw for throwing an exception Catch for taking an action for specific exception Try: The try block is one which can throw an exception. The code that we want to monitor for exception is placed within the try block. Try block is the scope of the exceptional generation. It contains the throw statement or a function containing throw statement. Syntax: Try { // code for raising exception } Throw: It is a mechanism to derive the exception Its a single statement with keyword throw. The identifier following is the name of the variable being thrown. After executing the throw statement, the control now permanently transferred to catch block, and the statement after close statement are executed. Syntax: throw e where is throw is the keyword and e is the object name or nameless object Catch: It must be used after the try block. This is the section where the exception is handled. Within the try block, calling a function with such a throw statement, exception is said to be thrown, then the exception is handled by the catch block. Syntax: Catch(e) { Action for handling an exception } e is the object name or nameless object Example : #include<iostream.h> #include<conio.h> class myexception { int num; public: myexception(int a) { num=a; } class DIVIDE //abstract class used to throw exception { Velammal Institute Of Technology Page 42

}; int divide(int x) { try { If (x==0) throw DIVIDE(); // raise Exception cout<< \nThe statement will not be executed\n; else { cout<<\nTrying division succeeds; cout<<num/x; } } catch(myexception::DIVIDE) { cout<<\nException divided by zero; } }; void main() { myexception ex(10); ex.divide(0); } In main() the statement ex.divide(0),calls the divide() function to perform the division operation, the statement if(x=0) used for checking zero division if yes, the the statement throw DIVIDE; detects the same and raises the exception by passing a nameless object of class type DIVIDE Throwing variables other than objects It is possible to throw other variables like character, integer and string etc., We can also catch them in a way as we catch objects. Example #include<iostream.h> #include<conio.h> class myexception { int num; public: myexception(int a) { num=a; } int divide(int x) { try { If (x==0) throw x; //raise exception cout<< \nThe statement will not be executed\n; else { cout<<\nTrying division succeeds; cout<<num/x; } } catch(int) Velammal Institute Of Technology Page 43

{ cout<<\nException divided by zero; } }; void main() { myexception ex(10); ex.divide(0); } In main() the statement ex.divide(0),calls the divide() function to perform the division operation, the statement if(x=0) used for checking zero division if yes, the the statement throw x; detects the same and raises the exception by passing the integer value xthe catch block following the try block will catch the exception and handles it Using Multiple Catch It is possible to use more than one catch block for a single try block to handle different exception. At first matching catch block will be executed. If no matching catch block is found, the exception is passed on next catch block into hierarchy. Example #include<iostream.h> #include<conio.h> class myexception { int exnumber; string exmessage; public: myexception(int errno,string errmsg) { exnumber=errno; exmessage=errmsg; } Void showEx() { Cout<<exnumber; Cout<<exmessage; } Void exgen() { try { Myexception error(10,error testing); Cout<<Press 1 for int 2 for char,3 for object; int reply; cin>>reply; switch(reply) { Case 1: Throw 10; Case 2: Throw a; Case 3: Throw error; } } Catch(int x) { Cout<<integer exception<<x; Velammal Institute Of Technology Page 44

} Catch(int c) { Cout<<integer exception<<c; } Catch(my exception my) { Cout<<integer exception<<my.exshow(); } }; Void main() { Exgen(); } Catch All It is possible to catch all type of exceptions in a single catch section. We can use catch() for the same. The catch block should have three dots as an argument to catch any number of exception Example #include<iostream.h> #include<conio.h> class myexception { int exnumber; string exmessage; public: myexception(int errno,string errmsg) { exnumber=errno; exmessage=errmsg; } Void showEx() { Cout<<exnumber; Cout<<exmessage; } Void exgen() { Myexception error(10,error testing); Cout<<Press 1 for int 2 for char,3 for object; int reply; cin>>reply; switch(reply) { Case 1: Throw 10; Case 2: Throw a; Case 3: Throw error; } Catch() { Cout<<anything thrown caught here; } }; Void main() Velammal Institute Of Technology Page 45

{ Try { Exgen(); } } Rethrowing an exception If we want to catch the exception in the function N and also want to pass it to any other function, its is achieved by rethrowing an exception after catching it Example #include<iostream.h> #include<conio.h> class myexception { int exnumber; string exmessage; public: myexception(int errno,string errmsg) { exnumber=errno; exmessage=errmsg; } Void showEx() { Cout<<exnumber; Cout<<exmessage; } Void exgen() { Myexception error(10,error testing); Cout<<Press 1 for int 2 for char,3 for object; int reply; cin>>reply; switch(reply) { Case 1: Throw 10; Case 2: Throw a; Case 3: Throw error; } Catch(int x) { Throw; } Catch(int c) { Throw; } Catch(my exception my) { Throw; } }; Void main() Velammal Institute Of Technology Page 46

{ Try { Exgen(); } Catch(int x) { Cout<<integer exception<<x; } Catch(int c) { Cout<<integer exception<<c; } Catch(my exception my) { Cout<<integer exception<<my.exshow(); } }

Exception specification: Syntax: Function name(arg list)throw (datatype exception allowed) { Function body } Example: #include<iostream.h> #include<conio.h> class myexception { int num; public: my exception(int a) { num=a; } class DIVIDE { }; int divide(int x) Throw(int,float) // this function allowed only to throw int,float type exception { try { throw DIVIDE (); cout<< the statement will not be executed; else Velammal Institute Of Technology Page 47 It is possible to specify what type of exception can be thrown by function. It is possible by adding throw keyword with function definition and possible type of exception to be thrown in parenthesis. If other than int and character type exception acquires, then a built-in function named unexpected which in turn calls terminate().

{ cout<<trying division succeeded<<num/x; } catch(my exception::DIVIDE) { Cout<<object exception caughted; } } }; void main() { my exception ex(10); ex.divide(0); }

Terminate function: Syntax: Void main() { Set_terminate(myterminate); } When the exceptional handling does not find any catch block for thrown exception terminate() is called throw terminate the program execution. It is a built-in function, when it is invoked internally it calls the abort function, to cancel the program execution in the event of runtime errors related to exception. The user is permitted to define and specify their own terminate function in place of built-in terminate(); By this way the user is permitted to close all open files deallocate resources before quitting the program.

//set to call our own terminate function

Void myterminate() // our own terminate function { //this cod will close all open files, deallocate memory and close all connections// Exit(-1) } Example #include<iostream.h> #include<conio.h> class myexception { int exnumber; string exmessage; public: myexception(int errno,string errmsg) { exnumber=errno; exmessage=errmsg; } Void showEx() { Velammal Institute Of Technology Page 48

Cout<<exnumber; Cout<<exmessage; } Void exgen() { try { Myexception error(10,error testing); Cout<<Press 1 for int 2 for char,3 for object; int reply; cin>>reply; switch(reply) { Case 1: Throw 10; Case 2: Throw a; Case 3: Throw error; } } Catch() { Cout<<anything thrown caught here; } }; Void myterminate() // our own terminate function { //this cod will close all open files, deallocate memory and close all connections// Exit(-1) } Void main() { Exgen(); Void myterminate(); Set_terminate(myterminate); } Unexpected function: The unexpected() function is called when the function throws an exception not listed in its exception specification. Internally it calls terminate function, to terminate the program execution. It is possible to define and use our own unexpected function instead of built-in unexpected function. The function set_unexpected function is used to call our own unexpected function instead of built in unexpected function.

// set to call our own terminate function

Example: #include<iostream.h> #include<conio.h> class myexception { int exnumber; string exmessage; public: Velammal Institute Of Technology Page 49

myexception(int errno,string errmsg) { exnumber=errno; exmessage=errmsg; } Void showEx() { Cout<<exnumber; Cout<<exmessage; } Void exgen() throw() { try { Myexception error(10,error testing); Cout<<Press 1 for int 2 for char,3 for object; int reply; cin>>reply; switch(reply) { Case 1: Throw 10; Case 2: Throw a; Case 3: Throw error; } } Catch() { Cout<<anything thrown caught here; } }; Void myunexcepted() // our own terminate function { //this cod will close all open files, deallocate memory and close all connections// Exit(-1) } Void main() { Exgen(); Void myunexcepted(); Set_unexpected(myunexpected); } Uncaught exception function: The thrown exception is considered as catch whin it is corresponding block hs been ended. In order to check whither the thrown exception is currently being processed we can use a standard function called uncaught exception(). It is not possible to handle two exception simultaneously ie., it is not possible to process second exception before, the completion of first one. In this situation where the first one is not completely process, the second one is being thrown. A function built-in exception class called uncaught_exception comes into effect. Page 50

// set to call our own terminate function

Velammal Institute Of Technology

Example : If(uncaught_exception()) { Do not call the function which might throw an exception } Else { Follow the natural sequence of the destruction }

Velammal Institute Of Technology

Page 51

Das könnte Ihnen auch gefallen