Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore BCA122_OOPS(Draft 2)(1)

BCA122_OOPS(Draft 2)(1)

Published by Teamlease Edtech Ltd (Amita Chitroda), 2021-05-14 07:57:21

Description: BCA122_OOPS(Draft 2)(1)

Search

Read the Text Version

Function Overriding Example To override a function you must have the same signature in child class. By signature I mean the data type and sequence of parameters. Here we don’t have any parameter in the parent function so we didn’t use any parameter in the child function. #include<iostream> usingnamespace std; classBaseClass{ public: void disp(){ cout<<\"Function of Parent Class\"; } }; classDerivedClass:publicBaseClass{ public: void disp(){ cout<<\"Function of Child Class\"; } }; int main(){ DerivedClass obj =DerivedClass(); obj.disp(); 150 CU IDOL SELF LEARNING MATERIAL (SLM)

return0; } Output: Function of ChildClass Note: In function overriding, the function in parent class is called the overridden function and function in child class is called overriding function. 6.7 MEMBER CLASSES: NESTING OF CLASSES. A nested class is a class that is declared in another class. The nested class is also a member variable of the enclosing class and has the same access rights as the other members. However, the member functions of the enclosing class have no special access to the members of a nested class. A program that demonstrates nested classes in C++ is as follows. Example #include<iostream> usingnamespace std; class A { public: class B { private: int num; public: 151 CU IDOL SELF LEARNING MATERIAL (SLM)

void getdata(int n){ num = n; } void putdata(){ cout<<\"The number is \"<<num; } }; }; int main(){ cout<<\"Nested classes in C++\"<< endl; A :: B obj; obj.getdata(9); obj.putdata(); return0; } Output Nested classes in C++ The number is 9 In the above program, class B is defined inside the class A so it is a nested class. The class B contains a private variable num and two public functions getdata() and putdata(). The function getdata() takes the data and the function putdata() displays the data. This is given as 152 CU IDOL SELF LEARNING MATERIAL (SLM)

follows. class A { public: class B { private: int num; public: void getdata(int n){ num = n; } void putdata(){ cout<<\"The number is \"<<num; } }; }; In the function main(), an object of the class A and class B is defined. Then the functions getdata() and putdata() are called using the variable obj. This is shown below. cout<<\"Nested classes in C++\"<< endl; A :: B obj; obj.getdata(9); 153 CU IDOL SELF LEARNING MATERIAL (SLM)

obj.putdata(); 6.8SUMMARY  Inheritance is the capability of one class to inherit properties from another class.  It supports reusability of code and is able to simulate the transitive nature of real life objects. Inheritance has many forms: Single inheritance, multiple inheritance, hierarchical inheritance, multilevel inheritance and hybrid inheritance.  A subclass can derive itself publicly, privately or protectedly. The derived class constructor is responsible for invoking the base class constructor, the derived class can directly access only the public and protected members of the base class.  When a class inherits from more than one base class, this is called multiple inheritance.  A class may contain objects of another class inside it. his situation is called nesting of objects and in such a situation, the contained objects are constructed first before constructing the objects of the enclosing class.  Single Inheritance: Where a class inherits from a single base class, it is known as single inheritance.  Multilevel Inheritance: When the inheritance is such that the class. A serves as a base class for a derived class B which is turn serves as a base class for the derived class C. This type of inheritance is called ‘Multilevel Inheritance.  Both inheritance and composition allow you to create a new type from existing types, and both embed sub objects of the existing types inside the 154 CU IDOL SELF LEARNING MATERIAL (SLM)

new type. Typically, however, you use composition to reuse existing types as part of the underlying implementation of the new type and inheritance when you want to force the new type to be the same type as the base class (type equivalence guarantees interface equivalence).  Multiple Inheritance: A class inherit the attributes of two or more classes. This mechanism is known as Multiple Inheritance.’  Hybrid Inheritance: The combination of one or more types of the inheritance.  Overriding helps in: Redefining inherited methods in subclasses. In redefinition declaration should be identical, code may be different. It is like having another version of the same product. 6.9KEY WORDS/ABBREVIATIONS  Abstract Class: A class serving only a base class for other classes and no objects of which are created.  Base class: A class from which another class inherits. (Also called super class)  Containership: The relationship of two classes such that the objects of a class are enclosed within the other class.  Derived class: A class inheriting properties from another class. (also called sub class) Inheritance: Capability of one class to inherit properties from another class.  Inheritance Graph: The chain depicting relationship between a base class and derived class. Visibility Mode: The public, private or protected specifier that controls the visibility and availability of a member in a class. 155 CU IDOL SELF LEARNING MATERIAL (SLM)

6.10LEARNINGACTIVITY 1. Write program on Example of Multiple Inheritances: Bank __________________________________________________________________________ __________________________________________________________________________ 2. We want to calculate the total marks of each student of a class in Physics, Chemistry and Mathematics and the average marks of the class. The number of students in the class is entered by the user. Create a class named Marks with data members for roll number, name and marks. Create three other classes inheriting the Marks class, namely Physics, Chemistry and Mathematics, which are used to define marks in individual subject of each student. Roll number of each student will be generated automatically. Write program for it. __________________________________________________________________________ __________________________________________________________________________ 6.11 UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE) A. Descriptive Types Questions 1. Consider a situation where three kinds of inheritance are involved. Explain this 156 CU IDOL SELF LEARNING MATERIAL (SLM)

situation with an example. 2. What is the difference between protected and private members? 3. Scrutinize the major use of multilevel inheritance. 4. Discuss a situation in which the private derivation will be more appropriate as compared to public derivation. 5. Identify program for the classes Car and Paccar are to modify to allow objects to be created and destroyed. In addition, the class Truck is to be added to the class hierarchy. B. Multiple Choice Questions 1. Which among the following best describes the Inheritance? (a) Copying the code already written (b) Using the code already written once (c) Using already defined functions in programming language (d) Using the data and functions into derived segment 2. How many basic types of inheritance are provided as OOP feature? (a) 4 (b) 3 (c) 2 (d) 1 3. Which among the following best defines single level inheritance? (a) A class inheriting a derived class (b) A class inheriting a base class (c) A class inheriting a nested class (d) A class which gets inherited by 2 classes 4. Which among the following is correct for multiple inheritance? 157 (a) class student{public: int marks;}s; class stream{int total;}; class topper: public student, public stream{ }; CU IDOL SELF LEARNING MATERIAL (SLM)

(b) class student{int marks;}; class stream{ }; class topper: public student{ }; (c) class student{int marks;}; class stream:public student{ }; (d) class student{ }; class stream{ }; class topper{ }; 5. Which programming language doesn’t support multiple inheritance? (a) C++ and Java (b) C and C++ (c) Java and SmallTalk (d) Java Answers 1. (d), 2. (a), 3. (b), 4. (a), 5. (d) 6.12REFERENCES  Nell B. Dale, Study guide for C++ Plus Data Structure, Academic Internet Publishers  Yashavant Kanetkar, C++ Programming, 1st Edition, BPB Publication.  Kyle Loudon, C++ Pocket Reference 1st Edition, O’reilly Publication  http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx  http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/  https://www.w3schools.com/java/java_inheritance.asp.  Inheritance and Its Type in Object Oriented Programming Using C++ 18 Sep 2019Dr Mehul Patel  Uses and Abuses of Inheritance, Part 1 ++ Report, 10(9), October 1998. 158 CU IDOL SELF LEARNING MATERIAL (SLM)

159 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 7 POLYMORPHISM 160 Structure 7.0 LearningObjectives 7.1 Introduction 7.2 Introduction &Types of polymorphism 7.2.1 Compile time Polymorphism 7.2.2 Runtime Polymorphism 7.3 Function overloading 7.4 Operator overloading 7.5 Rules for overloading operators 7.6 Overloading of unary operators 7.7 Overloading of binaryoperators 7.7.1 Using friend function 7.7.2 Using member function 7.8 Summary 7.9 KeyWords/Abbreviations 7.10 LearningActivity 7.11 Unit End Questions (MCQ andDescriptive) 7.12 References CU IDOL SELF LEARNING MATERIAL (SLM)

7.0 LEARNINGOBJECTIVES After studying this unit, you will be able to:  Explain the polymorphismand its type  Discuss Function overloading  Discuss operator overloading  Explain Overloading of unary & binary operators 7.1 INTRODUCTION The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance .C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.By default, C++ matches a function call with the correct function definition at compile time. This is called static binding. You can specify that the compiler match a function call with the correct function definition at run time; this is called dynamic binding. You declare a function with the keyword virtual if you want the compiler to use dynamic binding for that specific function.Conceptually an object may have only data members specifying its attributes. However, such an object would serve no useful purpose. For the purpose of establishing communication with the object it is necessary that the object provide methods, which are C like functions. Though C++ functions are very similar to C functions, yet they differ significantly as you will discover in this unit.C++ provides a rich collection of operators. You have already seen the meaning and uses of many such operators in previous units. One special feature offered by C++ is operator overloading. This feature is necessary in a programming language supporting objects oriented features 161 CU IDOL SELF LEARNING MATERIAL (SLM)

7.2 INTRODUCTION & TYPES OF POLYMORPHISM Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. This means that a general class of operations may beaccessed in the same manner even though specific actions associated with each operation may differ. Polymorphism is extensively used in implementing inheritance as shown below. Fig 7.1 Polymorphism implement in inheritance Polymorphism can be implemented using operator and function overloading, where the same operator and function works differently on different arguments producing different results. These polymorphisms are brought into effect at compile time itself, hence is known as early binding, static binding, static linking or compile time polymorphism. However, ambiguity creeps in when the base class and the derived class both have a function with same name. For instance, let us consider the following code snippet. 162 CU IDOL SELF LEARNING MATERIAL (SLM)

Since, both the functions aa. display () and bb. display () is same but at in different classes, there is no overloading, and hence early binding does not apply. The appropriate function is chosen at the run time – run time polymorphism. C++ supports run-time polymorphism by a mechanism called virtual function. It exhibits late binding or dynamic linking. As stated earlier, polymorphism refers to the property by which objects belonging to different classes are able to respond to the same message, but in different forms. Therefore, an essential feature of polymorphism is the ability to refer to objects without any regard to their classes. It implies that a single pointer variable may refer to object of different classes. However, a base pointer, even if is made to contain the address of the derived class, always executes the function in the base class. The compiler ignores the content of the pointer andchooses the member function that matches the type of the pointer. Thus, the polymorphism Notes stated above cannot be implemented by this mechanism. 163 CU IDOL SELF LEARNING MATERIAL (SLM)

Fig 7.2 Polymorphism in C++ The biggest advantage of polymorphism is creation of reusable code by programmer‟s classes once written, tested and implemented can be easily reused without caring about what’s written in the case.  Polymorphic variables help with memory use, in that a single variable can be used to store multiple data types (integers, strings, etc.) rather than declaring a different variable for each data format to be used. Polymorphism is a powerful feature of the object oriented programming language C++.  Applications are Easily Extendable: Once an application is written using the concept of polymorphism, it can easily be extended, providing new objects that conform to the original interface. It is unnecessary to recompile original programs by adding new types. Only re- linking is necessary to exhibit the new changes along with the old application. This is the greatest achievement of C++ object-oriented programming. In programming language, there has always been a need for adding and customizing. By utilizing the concept of polymorphism, time and work effort is reduced in addition to making future maintenance easier.  It provides easier maintenance of applications.  It helps in achieving robustness in applications. 164 CU IDOL SELF LEARNING MATERIAL (SLM)

Types of Polymorphism Polymorphism is a feature of OOPs that allows the object to behave differently in different conditions. In C++ we have two types of polymorphism: 1) Compile time Polymorphism – This is also known as static (or early) binding. 2) Runtime Polymorphism – This is also known as dynamic (or late) binding. 7.2.1 Compile time Polymorphism Function overloading and Operator overloading are perfect example of Compile time polymorphism. Compile time Polymorphism Example In this example, we have two functions with same name but different number of arguments. Based on how many parameters we pass during function call determines which function is to be called, this is why it is considered as an example of polymorphism because in different conditions the output is different. Since, the call is determined during compile time that’s why it is called compile time polymorphism. #include<iostream> usingnamespace std; classAdd{ public: int sum (int num1,int num2) { return num1+num2; } int sum (int num1,int num2,int num3) { 165 CU IDOL SELF LEARNING MATERIAL (SLM)

return num1+num2+num3; } }; int main(){ Add obj; //This will call the first function cout<<\"Output: \"<<obj.sum(10,20)<<endl; //This will call the second function cout<<\"Output: \"<<obj.sum(11,22,33); return0; } Output: Output:30 Output:66 7.2.2 Runtime Polymorphism Function overriding is an example of Runtime polymorphism. In case of function overriding we have two definitions of the same function, one is parent class and one in child class. The call to the function is determined at runtime to decide which definition of the function is to be called, that’s the reason it is called runtime polymorphism. Example of Runtime Polymorphism #include<iostream> 166 CU IDOL SELF LEARNING MATERIAL (SLM)

usingnamespace std; 167 class A { public: void disp(){ cout<<\"Super Class Function\"<<endl; } }; class B:public A{ public: void disp(){ cout<<\"Sub Class Function\"; } }; int main(){ //Parent class object A obj; obj.disp(); //Child class object B obj2; obj2.disp(); CU IDOL SELF LEARNING MATERIAL (SLM)

return0; } Output: SuperClassFunction SubClassFunction 7.3 FUNCTION OVERLOADING A function may take zero or more arguments when called. The number and type of arguments that a function may take is defined in the function itself. If a function call fails to comply by the number and type of argument(s), the compiler reports the same as error. Suppose we write a function named sum to add two numerical values given as arguments. One can write the function as: Now suppose we want the function to take float type argument then the function definition must be changed as: 168 CU IDOL SELF LEARNING MATERIAL (SLM)

This can be very tiring and extremely difficult to remember all the names. Function overloading is a mechanism that allows a single function name to be used for different functions. The compiler does the rest of the job. It matches the argument numbers and types to determine which functions are being called. Thus we may rewrite the above listed functions using function overloading as: 169 CU IDOL SELF LEARNING MATERIAL (SLM)

Overloaded functions have the same name but different number and type of arguments. They can differ either by number of arguments or type of arguments or both. However, two overloaded function cannot differ only by the return type. 7.4 OPERATOR OVERLOADING Overloading an operator simply means attaching additional meaning and semantics to an operator. It enables an operator to exhibit more than one operation polymorphically, as illustrated below: You know that addition operator (+) is essentially a numeric operator and therefore, requires two number operands. It evaluates to a numeric value, which is equal to 170 CU IDOL SELF LEARNING MATERIAL (SLM)

the sum of the two operands. Evidently this cannot be used in adding two strings. However, we can extend the operation of addition operator to include string concatenation. Consequently, the addition operator would work as follows: “COM” + “PUTER.should produce a single string “COMPUTER” This act of redefining the effect of an operator is called operator overloading. The original meaning and action of the operator however remains as it is. Only an additional meaning is added to it. Function overloading allows different functions with different argument list having the same name. Similarly an operator can be redefined to perform additional tasks. Operator overloading is accomplished using a special function, which can be a member function or friend function. The general syntax of operator overloading is: Here, operator is the keyword and is preceded by the return_type of the operation. To overload the addition operator (+) to concatenate two characters, the following declaration, which could be either member or friend function, would be needed: A simple and complete example 171 #include<iostream> using namespace std; class Complex { private: int real, imag; public: Complex(int r = 0, int i =0) {real = r; imag = i;} CU IDOL SELF LEARNING MATERIAL (SLM)

// This is automatically called when '+' is used with // between two Complex objects Complex operator + (Complex const &obj) { Complex res; res.real = real + obj.real; res.imag = imag + obj.imag; return res; } void print() { cout << real << \" + i\" << imag << endl; } }; int main() { Complex c1(10, 5), c2(2, 4); Complex c3 = c1 + c2; // An example call to \"operator+\" c3.print(); } Output: 172 CU IDOL SELF LEARNING MATERIAL (SLM)

12 + i9 7.5 RULES FOR OVERLOADING OPERATORS To overload any operator, we need to understand the rules applicable Let us revise some of them which have already been explored. Following are the operators that cannot be overloaded. Table 7.1 Operators that cannot be Overloaded 1. Operators already predefined in the C++ compiler can be only overloaded. Operator cannot change operator templates that is for example the increment operator ++ is used only as unary operator. It cannot be used as binary operator. 2. Overloading an operator does not change its basic meaning. For example assume the + operator can be overloaded to subtract two objects. But the code becomes unreachable 173 CU IDOL SELF LEARNING MATERIAL (SLM)

3. Unary operators, overloaded by means of a member function, take no explicit argument and return no explicit values. But, those overloaded by means of a friend function take one reference argument (the object of the relevant class). 4. Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments Table 7.2 Operator overloading rules 5. Overloaded operators must either be a non-static class member function or a global function. A global function that needs access to private or protected class members must be declared as a friend of that class. A global function must take at least one argument that is of class or enumerated type or that is a reference to a class or enumerated type. Example: 174 CU IDOL SELF LEARNING MATERIAL (SLM)

7.6 OVERLOADING UNARY OPERATORS In case of unary operator overloaded using a member function no argument is passed to the function whereas in case of a friend function a single argument must be passed. Following program overloads the unary operator to negate an object. The operator function defined outside the class negates the individual data members of the class integer. // C++ program to show unary operator overloading 175 #include <iostream> using namespace std; class Distance { public: // Member Object int feet, inch; // Constructor to initialize the object's value CU IDOL SELF LEARNING MATERIAL (SLM)

Distance(int f, int i) { this->feet = f; this->inch = i; } // Overloading(-) operator to perform decrement // operation of Distance object void operator-() { feet--; inch--; cout << \"\\nFeet & Inches(Decrement): \" << feet << \"'\" << inch; } }; // Driver Code int main() { // Declare and Initialize the constructor 176 CU IDOL SELF LEARNING MATERIAL (SLM)

Distance d1(8, 9); // Use (-) unary operator by single operand -d1; return 0; } Output: Feet & Inches(Decrement): 7'8 In the above program, it shows that no argument is passed and no return_type value is returned, because unary operator works on a single operand. (-) operator change the functionality to its member function. Note: d2 = -d1 will not work, because operator-() does not return any value. 7.7 OVERLOADING BINARY OPERATORS Binary Operators are operators, which require two operands to perform the operation. When they are overloaded by means of member function, the function takes one argument, whereas it takes two arguments in case of friend function. This will be better understood by means of the following program. // C++ program to show binary operator 177 overloading #include <iostream> using namespace std; class Distance { CU IDOL SELF LEARNING MATERIAL (SLM)

public: 178 // Member Object int feet, inch; // No Parameter Constructor Distance() { this->feet = 0; this->inch = 0; } // Constructor to initialize the object's value // Parametrized Constructor Distance(int f, int i) { this->feet = f; this->inch = i; } // Overloading (+) operator to perform addition of // two distance object CU IDOL SELF LEARNING MATERIAL (SLM)

Distance operator+(Distance& d2) // Call by 179 reference { // Create an object to return Distance d3; // Perform addition of feet and inches d3.feet = this->feet + d2.feet; d3.inch = this->inch + d2.inch; // Return the resulting object return d3; } }; // Driver Code int main() { // Declaring and Initializing first object Distance d1(8, 9); // Declaring and Initializing second object Distance d2(10, 2); // Declaring third object CU IDOL SELF LEARNING MATERIAL (SLM)

Distance d3; // Use overloaded operator d3 = d1 + d2; // Display the result cout << \"\\nTotal Feet & Inches: \" << d3.feet << \"'\" << d3.inch; return 0; } Output: Total Feet & Inches: 18'11 7.7.1 Using Friend Function The following program is the same as previous one. The only difference is that we use a friend function to find the sum of two objects. Note that an argument is passed to this friend function 180 CU IDOL SELF LEARNING MATERIAL (SLM)

181 CU IDOL SELF LEARNING MATERIAL (SLM)

You should see the following output. value = 11 value = 22 value = 33 Friend function being a non-member function does not belong to any class. This function is invoked like a normal function. Hence the two objects that are to be added have to be passed as arguments exclusively. 7.7.2 Using Member Function In the unit on overloading the arithmetic operators, you learned that when the operator does not modify its operands, it’s best to implement the overloaded operator as a friend function 182 CU IDOL SELF LEARNING MATERIAL (SLM)

of the class. For operators that do modify their operands, we typically overload the operator using a member function of the class. Overloading operators using a member function is very similar to overloading operators using a friend function. When overloading an operator using a member function: 1. The leftmost operand of the overloaded operator must be an object of the class type. 2. The leftmost operand becomes the implicit *this parameter. All other operands become function parameters. Most operators can actually be overloaded either way, however there are a few exception cases: 3. If the leftmost operand is not a member of the class type, such as when overloading operator+ (int, YourClass), or operator<<(ostream&, YourClass), the operator must be overloaded as a friend. 4. The assignment (=), subscript ([]), call (()), and member selection (->) operators must be overloaded as member functions. Overloading the unary negative (–) operator the negative operator is a unary operator that can be implemented using either method. Before we show you how to overload the operator using a member function, here’s a reminder of how we overloaded it using a friend function: 183 CU IDOL SELF LEARNING MATERIAL (SLM)

Now let’s overload the same operator using a member function instead: You’ll note that this method is pretty similar. However, the member function version of operator doesn’t take any parameters! Where did the parameter go? In the lesson on the hidden this pointer, you learned that a member function has an implicit *this pointer which always points to the class object the member function is working on. The parameter we had to list explicitly in the friend function version (which doesn’t have a *this pointer) becomes the implicit *this parameter in the member function version. Overloading the binary addition (+) operator Let’s take a look at an example of a binary operator overloaded both ways. First, overloading operator+ using the friend function: 184 CU IDOL SELF LEARNING MATERIAL (SLM)

Now, the same operator overloaded using the member function method: Our two-parameter friend function becomes a one-parameter member function, because the leftmost parameter (cCents) becomes the implicit *this parameter in the member function 185 CU IDOL SELF LEARNING MATERIAL (SLM)

version.Most programmers find the friend function version easier to read than the member function version, because the parameters are listed explicitly. Furthermore, the friend function version can be used to overload some things the member function version cannot. For example, friend operator+(int, cCents) cannot be converted into a member function because the leftmost parameter is not a class object. However, when dealing with operands that modify the class itself (e.g. operators =, +=, -=, ++, -, etc…) the member function method is typically used because C++ programmers are used to writing member functions (such as access functions) to modify private member variables. Writing friend functions that modify private member variables of a class is generally not considered good coding style, as it violates encapsulation. 7.8SUMMARY  Early binding refers to the events that occur at compile time while late binding means selecting function during the execution. The late binding is implemented through virtual function.  An abstract base class will not be used to create object, but exist only to act as a base class Notes of other classes.  Polymorphism allows the program to use the exactly same function name with exactly same arguments in both a base class and its subclasses. It refers to the implicit ability of a function to have different meanings in different contexts.  C++ supports the run time polymorphism with the help of virtual function by using the concept of dynamic binding. Dynamic binding requires use of pointers to objects. Pointers to objects of a base class type are compatible with pointers to objects of a derived class.  Run time polymorphism is achieved only when a virtual function is accessed through a pointer to the base class. If a virtual function is defined in the base class, it need not be necessarily redefined in the derived class. Such virtual 186 CU IDOL SELF LEARNING MATERIAL (SLM)

functions (equated to zero) are called pure virtual functions. A class containing such pure function is called an abstract class.  The keyword operator is used to overload an operator, and the resulting operator will adopt the meaning supplied by the programmer.  Closely related to operator overloading is the issue of type conversion. Some conversions take place between user defined types and basic types  Two approaches are used in such conversion: A one argument constructor changes a basic type to a user defined type, and a conversion operator converts a user-defined type to a basic type.  When one user-defined type is converted to another, either approach can be used.  The signature of the function declared as pure virtual in base class must strictly agree with the signature of the function in child class that implements the pure virtual function.  The signature of the function declared as pure virtual in base class must strictly agree with the signature of the function in child class that implements the pure virtual function. 7.9KEY WORDS/ABBREVIATION  Operator Overloading: Attaching additional meaning and semantics to an operator. It enables to exhibit more than one operations polymorphically.  Unary Operators: Unary operators operate on one operand (variable or constant). There are two types of unary operators- increment and decrement.  Abstract Base Class: An abstract base class will not be used to create object, but exist 187 CU IDOL SELF LEARNING MATERIAL (SLM)

only to act as a base class of other classes.  Late Binding: Selecting functions during the execution. Though late binding requires some overhead it provides increased power and flexibility.  Polymorphism: Polymorphism allows the program to use the exactly same function name with exactly same arguments in both a base class and its subclasses. 7.10 LEARNINGACTIVITY 1. Which operators are not allowed to be overloaded? __________________________________________________________________________ __________________________________________________________________________ 2. Make function in a class Vehicle may have to make a Vehicle with red color. A class called Four-wheeler, derived or inherited from Vehicle, may have to use a blue background and 4 tires as wheels. Write program for this. __________________________________________________________________ __________________________________________________________________ 7.11UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE) A. Descriptive Types Questions 1. What will be the output of the following program snippet? Explain. 188 CU IDOL SELF LEARNING MATERIAL (SLM)

2. Create a simple “shape” hierarchy: a base class called Shape and derived classes called Circle, Square, and Triangle. In the base class, make a virtual function called draw(), and override this in the derived classes. Make an array of pointers to Shape objects that you create on the heap (and thus perform upcasting of the pointers), and call draw() through the base-class pointers, to verify the behavior of the virtual function. If your debugger supports it, single-step through the code 3. Create an air-traffic control system with base-class Aircraft and various derived types. Create a Tower class with a vector that sends the appropriate messages to the various aircraft under its control 4. Write a program which uses a polymorphism with pointers. 5. Create a class that has a data member and a derived class that adds another data member. Write a non-member function that takes an object of the base class by value and prints out the size of that object using sizeof. In main( ) create an object of the derived class, print out its size, and then call your function. Explain what happens B. Multiple Choice Questions 1. Compile time polymorphism in C++ language is (a)Operator overloading (b)Function overloading (c)Function overriding (d) a & b 2. C++ abstract class can contain (a)Pure virtual function (b)Non-virtual function (c)Only pure virtual function 189 CU IDOL SELF LEARNING MATERIAL (SLM)

(d)Both pure virtual and non-virtual function 3. False statements about function overloading is (a)Defining multiple functions with same name in a class is called function overloading (b)Overloaded function must differ in their order and types of arguments. (c)Overloaded functions should be preceded with virtual keyword (d) No statement is false 4. Following keyword is used before a function in a base class to be overridden in derived class in C++ (a)override (b)virtual (c)void (d) none 5. Which of the following cannot be overloaded in C++? (a)Increment operator (b)Constructor (c)Destructor (d)New and delete operator Answers 190 1. (d), 2. (b), 3. (d), 4. (a), 5. (c) CU IDOL SELF LEARNING MATERIAL (SLM)

7.12SUGGESTED READING  The C++ Programming Language, Bjarne Stroustroup, 3rd edition, Addison Wesley, 1997 2)  C++: The Complete Reference, H. Shildt, 4th edition, TMH, New Delhi, 2004  Thinking in C++, Volume 1, 2nd Edition Bruce Eckel  Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.  http://www.artima.com/cppsource/pure_virtual.html  http://publib.boulder.ibm.com/infocenter/comphelp/v8v101index.jsp?topic=%2Fcom .ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr142.htm  http://www.bogotobogo.com/cplusplus  http://www.gamespp.com/c/introductionToCppMetrowerksLesson11.html  Better alternative Run-Time Polymorphism in C++: A practical approach in OO design for machine intelligence Publisher: IEEE  External Polymorphism An Object Structural Pattern for Transparently Extending C++ Concrete Data Types Chris Cleeland and Douglas C. Schmidt 191 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT8 EXCEPTION HANDLING Structure 8.0. LearningObjectives 8.1. Introduction 8.2. Exceptions 8.2.1 Try 8.2.2 Throw 8.2.3 Catch 8.3. Throwing an Exceptions 8.4. Catching an exception 8.5. Summary 8.6. KeyWords/Abbreviations 8.7. LearningActivity 8.8. Unit End Questions (MCQ andDescriptive) 8.9. References 192 CU IDOL SELF LEARNING MATERIAL (SLM)

8.0 LEARNINGOBJECTIVES After studying this unit, you will be able to:  Explain the basic concepts of exception handling  Discuss Try, Throw, Catch, Throw exceptions  Discuss Throwing and Exception  Discuss Catching an Exception 8.1 INTRODUCTION When we develop a program, we expect the program does what it is supposed to do without any error. Many operations, including object instantiation and file processing, are subject to failures that may go beyond errors. Out-of-memory conditions, for instance, can occur even when your program is running correctly. - As an example, for typical application program the highest layer may consist of graphic user interface (GUI) part that provide interface for users. These high-level components interact with objects, which in turn encapsulate the application programming interface (API) routines. - At a lower level, the API routines may interact with the operating system. The operating system itself invokes system services that deal with low-level hardware resources such as physical memory, file systems, and security modules. In general, runtime errors are detected in these lower code layers should not be handled by themselves. - To handle an error appropriately, higher-level components have to be informed that an error has occurred. Generally, error handling consists of detecting an error and notifying the components that are in charge. These components in turn attempt to recover from the error or terminate the program properly. 193 CU IDOL SELF LEARNING MATERIAL (SLM)

- From thesimplest one, we may use a proper prompting, for example: Enter two integer separated by space: 8.2EXCEPTIONS An exception occurs when an unexpected error or unpredictable behaviors happened on your program not caused by the operating system itself. These exceptions are handled by code which is outside the normal flow of control and it needs an emergency exit. - Compared to the structured exception handling, returning an integer as an error flag is problematic when dealing with objects. The C++ exception-handling can be a full-fledged object, with data members and member functions. - Such an object can provide the exception handler with more options for recovery. A clever exception object, for example, can have a member function that returns a detailed verbal description of the error, instead of letting the handler look it up in a table or a file. C++ has incorporated three operators to help us handle these situations: try, throw and catch. The following is the try, throw…catch program segment example: In grammar form: 194 CU IDOL SELF LEARNING MATERIAL (SLM)

8.2.1try A try block is a group of C++ statements, enclosed in curly braces { }, that might cause an exception. This grouping restricts the exception handlers to the exceptions generated within the try block. Each try block may have one or more associated catch blocks. If no exception is thrown during execution of the guarded section, the catch clauses that follow the try block are not executed or bypassed. Execution continues at the statement after the lastcatch clause following the try block in which the exception was thrown. If an exception is thrown during execution of the guarded section or in any routine the guarded section calls either directly or indirectly such as functions, an exception object will be created from the object created by the throw operand. At this point, the compiler looks for a catch clause in a higher execution context that can handle an exception of the type thrown or a catch handler that can handle any type of exception. The compound-statement after the try keyword is the guarded section of code. syntax for using try/catch as follows − try { // protected code } catch( ExceptionName e1 ) { // catch block 195 CU IDOL SELF LEARNING MATERIAL (SLM)

} catch( ExceptionName e2 ) { // catch block } catch( ExceptionName eN ) { // catch block } 8.2.1 throw The throw statement is used to throw an exception and its value to a matching catch exception handler. A regular throw consists of the keyword throw and an expression. The result type of the expression determines which catch block receives control. Within a catch block, the current exception and value may be re-thrown simply by specifying the throw keyword alone that is without the expression. The throw is syntactically similar to the operand of a return statement but here, it returns to the catch handler. 8.2.3catch A catch block is a group of C++ statements that are used to handle a specific thrown exception. One or more catch blocks, or handlers, should be placed after each try block. A catch block is specified by: 1. The keyword catch 2. A catch parameter, enclosed in parentheses (), which corresponds to a specific type of exception that may be thrown by the try block 3. A group of statements, enclosed in curly braces { }, whose purpose is to handle the exception The compound-statement after the catch keyword is the exception handler, and catches or handles the exception thrown by the throw-expression. The exception-declaration statement part indicates the type of exception the clause handles. The type can be any valid data type, including a C++ class. - If the exception-declaration statement part is just an ellipsis (...) such as, 196 CU IDOL SELF LEARNING MATERIAL (SLM)

catch(...) Then, the catch clause will handle any type of exception, including C exceptions and system or application generated exceptions such as divide by zero, memory protection and floating- point violations. Such a handler must be the last handler for its try block acting as default catch. The catch handlers are examined in order of their appearance following the try block. If no appropriate handler is found, the next dynamically enclosing try block is examined. This process continues until the outermost enclosing try block is examined if there are more than one try block. If a matching handler is still not found, or if an exception occurs while unwinding, but before the handler gets control, the predefined run-time function terminate() is called. If an exception occurs after throwing the exception, but before the unwinding begins, terminate () is also called. The catch block must go right after the try block without any line of codes between them. The order in which catch handlers appear is important, because handlers for a given try block are examined in order of their appearance. For example, it is an error to place the handler for a base class before the handler for a derived class. After a matching catch handler is found, subsequent handlers are not examined. That is why an ellipsis catch, catch(...) handler must be the last handler for its try block. Besides that, catch may be overloaded so that it can accept different types as parameters. In that case the catch block executed is the one that matches the type of the exception sent through the parameter of throw Program example: 197 CU IDOL SELF LEARNING MATERIAL (SLM)

Output: Program example for multiple catch: 198 CU IDOL SELF LEARNING MATERIAL (SLM)

Output 199 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook