• No results found

Chapter 6 Polymorphism

N/A
N/A
Protected

Academic year: 2021

Share "Chapter 6 Polymorphism"

Copied!
25
0
0

Loading.... (view fulltext now)

Full text

(1)Prof.Manoj S.Kavedia (9860174297)([email protected]). 66. Polymorphism. Syllabus Concepts of polymorphism, types of polymorphism, Overloading & overriding, Virtual function, Static & dynamic binding.. Polymorphism Q1.Define Polymorphism? Ans. The word ‘poly’ originated from a Greek word meaning many and ‘morphism’ from a Greek word meaning form, and thus ‘polymorphism’ means many forms. In object oriented programming, polymorphism refers to identically named methods (member functions) that have different behavior depending on the type of object they refer. Polymorphism is the process of defining a number of objects of different classes into a group and call the methods to carry out the operation of the objects using different function calls. Polymorphism means ‘to carry out different processing steps by functions having same messages’ - It treats objects of related classes in a generic manner. The keyword virtual is used to perform the polymorphism concept in C++. Polymorphism refers to the run time binding to a pointer to a method. It is one of the important of object-oriented programming. It needs one name and multiple Forms. The concept of polymorphism is implemented using function and operator overloading. The overloaded member functions are selected for invoking the function calls depending on the type and the number of arguments. When the function name and Prototype is same in the base class and derived class which is not an function overloading. But it is called a function overloading. Polymorphism is the ability of an object or reference to take many different forms at different instances. These are of two types one is the "compile time polymorphism" and other one is the "run-time polymorphism". Compile time polymorphism: In this method object is bound to the function call at the compile time itself. Run time polymorphism: In this method object is bound to the function call only at the run time.. 1.

(2) Prof.Manoj S.Kavedia (9860174297)([email protected]). PolyMorphism PolyMorphism. Compile Time Compile Time Polymorphism Polymorphism. Function Function OverLoading OverLoading. Operator Operator OverLoading OverLoading. Rum Time Rum Time Polymorphism Polymorphism. Virtual Virtual Function Function. Q2.Describe what is polymorphism? State its use?State features of polymorphism Ans. Polymorphism refers to the ability to call different functions by using only one type of function call. Suppose a programmer wants to code vehicles of different shapes such as circles, squares, rectangles, etc. One way to define each of these classes is to have a member function for each that makes vehicles of each shape. Another convenient approach the programmer can take is to define a base class named Shape and then create an instance of that class. The programmer can have array that hold pointers to all different objects of the vehicle followed by a simple loop structure to make the vehicle, as per the shape desired, by inserting pointers into the defined array. This approach leads to different functions executed by the same function call. Polymorphism is used to give different meanings to the same concept. This is the basis for Virtual function implementation. In polymorphism, a single function or an operator functioning in many ways depends upon the usage to function properly. In order for this to occur, the following conditions must apply: • All different classes must be derived from a single base class. In the above example, the shapes of vehicles (circle, triangle, rectangle) are from the single base class called Shape. • The member function must be declared virtual in the base class. In the above example, the member function for making the vehicle should be made as virtual to the base class. Features and Advantages of the concept of Polymorphism 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.0020By utilizing the concept of polymorphism, time and work effort is reduced in addition to making future maintenance easier. • Helps in reusability of code. 2.

(3) Prof.Manoj S.Kavedia (9860174297)([email protected]) • •. Provides easier maintenance of applications. Helps in achieving robustness in applications.. Q3.List different types of polymorphism Ans. C++ provides three different types of polymorphism. Virtual functions Function name overloading Operator overloading In addition to the above three types of polymorphism, there exist other kinds of polymorphism: • • •. • •. run-time compile-time. Q4.What is Binding? Ans.Binding refers to the act of associating an object or a class with its member. If we can call a method fn() on an object obj of a class CC, we say that the object obj is binded with the method fn(). This happens at compile time and is known as static or compile time binding. The calls to the virtual member functions are resolved during run-time. This mechanism is known as dynamic binding. The most prominent reason why a virtual function will be used is to have a different functionality in the derived class. The difference between a non-virtual member function and a virtual member function is, the non-virtual member functions are resolved at compile time. Q5.What is Early Binding or compile time or static Binding polymorphism Ans.Selecting a function in normal way, during compilation time is called as early binding or static binding or static linkage. During compilation time, the C++ compiler determines which function is used based on the parameters passed to the function or the function’s return type. The compiler then substitutes the correct function for each invocation. Such compiler based substitutions are called static linkage. By default, C++ follows early binding. With early binding, one can achieve greater efficiency. Function calls are faster in this case because all the information necessary to call the function are hard coded. The purest object oriented programming language like Small talk permits only run time binding of the methods, whereas C++ allows both compile time binding and run time binding. Q6.Write program to demonstrate compile time polymorphism Ans. Compile time Polymorphism #include <iostream> #include <conio.h> using namespace std; int Add(int nX, int nY) { return nX + nY; 3.

(4) Prof.Manoj S.Kavedia (9860174297)([email protected]) } int Subtract(int nX, int nY) { return nX - nY; } int Multiply(int nX, int nY) { return nX * nY; } int main() { int nX; cout << "Enter a number: "; cin >> nX; int nY; cout << "Enter another number: "; cin >> nY; int nOperation; do { cout << "Enter an operation (0=add, 1=subtract, 2=multiply): "; cin >> nOperation; } while (nOperation < 0 || nOperation > 2); int nResult = 0; switch (nOperation) { case 0: nResult = Add(nX, nY); break; case 1: nResult = Subtract(nX, nY); break; case 2: nResult = Multiply(nX, nY); break; } cout << "The answer is: " << nResult << endl; return 0; } Explanation Because Add(), Subtract(), and Multiply() are all direct function calls, the compiler will use early binding to resolve the Add(), Subtract(), and Multiply() function calls. The compiler will replace the Add() function call with an instruction that tells the CPU to jump to the address of the Add() function. The same holds true for Subtract() and Multiply(). 4.

(5) Prof.Manoj S.Kavedia (9860174297)([email protected]) Q7.What is Late Binding or dynamic Binding or run time polymorphism? Demostrate with the help of the program. Ans. Selecting functions during execution time is called late binding or dynamic binding or dynamic linkage. Late binding requires some overhead but provides increased power and flexibility. The late binding is implemented through virtual functions. An object of a class must be declared either as a pointer to a class or a reference to a class. In C++, one way to get late binding is to use function pointers. A function pointer is a type of pointer that points to a function instead of a variable. The function that a function pointer points to can be called by using the function call operator (()) on the pointer. For example, the following code calls the Add() function int Add(int nX, int nY) { return nX + nY; } int main() { // Create a function pointer and make it point to the Add function int (*pFcn)(int, int) = Add; cout << pFcn(5, 3) << endl; // add 5 + 3 return 0; } Calling a function via a function pointer is also known as an indirect function call. The following calculator program is functionally identical to the calculator example above, except it uses a function pointer instead of a direct function call #include <iostream> using namespace std; int Add(int nX, int nY) { return nX + nY; } int Subtract(int nX, int nY) { return nX - nY; } int Multiply(int nX, int nY) { return nX * nY; } 5.

(6) Prof.Manoj S.Kavedia (9860174297)([email protected]) int main() { int nX; cout << "Enter a number: "; cin >> nX; int nY; cout << "Enter another number: "; cin >> nY; int nOperation; do { cout << "Enter an operation (0=add, 1=subtract, 2=multiply): "; cin >> nOperation; } while (nOperation < 0 || nOperation > 2); // Create a function pointer named pFcn (yes, the syntax is ugly) int (*pFcn)(int, int); // Set pFcn to point to the function the user chose switch (nOperation) { case 0: pFcn = Add; break; case 1: pFcn = Subtract; break; case 2: pFcn = Multiply; break; } // Call the function that pFcn is pointing to with nX and nY as parameters cout << "The answer is: " << pFcn(nX, nY) << endl; return 0; } In this example, instead of calling the Add(), Subtract(), or Multiply() function directly, we’ve instead set pFcn to point at the function we wish to call. Then we call the function through the pointer. The compiler is unable to use early binding to resolve the function call pFcn(nX, nY) because it can not tell which function pFcn will be pointing to at compile time! Late binding is slightly less efficient since it involves an extra level of indirection. With early binding, the compiler can tell the CPU to jump directly to the function’s address. With late binding, the program has to read the address held in the pointer and then jump to that address. This involves one extra step, making it slightly slower. However, the advantage of late binding is that it is more flexible than early binding, because decisions about what function to call do not need to be made until run time. Q8.Define the overloading and overriding Ans. Overloading 6.

(7) Prof.Manoj S.Kavedia (9860174297)([email protected]) If you specify more than one definition for a function name or an operator in the same scope, you have overloaded that function name or operator. If you call an overloaded function name or operator, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.. OverRiding Define a new function with same name ( as in base class) in derived class is known as method override. In the derived class base class defined method is hided. Method overriding is redefining the method (member function) in the derived class with the same name as that of public method of the base class. hen a member function in the base class is overridden in the derived class, the object of the derived class cannot access the functions original definition from the base. It only can access the new definition implemented in the derived class. The question is, if overriding is opposite to that of inheritance then why do we use it ? The answer is simple. Inheritance can be used to reuse a class definition already available. Suppose if we want to reuse the available class but a single member function of the base is not satisfying your software requirements. That single function needs update. e solution is to directly modify that class and use it. Normally, every software component has the owner and only owner is supposed to modify the code. Others cannot modify it. Another reason for not directly modifying the available class is that class might be used by some other system which requires maintaining the original function definition. Therefore, the second solution is applied; create a new class definition from the original by inheriting it. In the new derived -class insert a function definition for the function which you want to modify. C++ gives you this flexibility of overriding functions from the base just by redefining it with the same name in the derived class. Software reusability gets widened due to overriding. Without which we would have reimplemented the whole class again keeping all but one functions same. Q9.State difference between function overloading and overriding Ans.. 7.

(8) Prof.Manoj S.Kavedia (9860174297)([email protected]) Overloading 1.Different functions have same name in same class.. Overriding 1.Different functions have same name in different class.. 2.In overloading, prototypes must differ in either in number of parameters or in their data type. 3.They can be static or non-static Members of the class.. 2.In overriding the prototype for function must match exactly to the one Specified in the base class 3.They must be Non Static. 4.Constructors cant be overrided 5.Use concept of Inheritance When an overridden methods is called from within the subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be overridden(hided).. Q10.Write C++ program to implement overriding of member function Ans. Example /* Program Overriding Member Functions */ #include <iostream.h> #include <string.h> /*----------------------Class Declaration-------------------------*/ 8.

(9) Prof.Manoj S.Kavedia (9860174297)([email protected]) class employee { char name[10]; int empno; public : void set(int, char*); void display_heading(); void display(); }; class manager : public employee { int no_of_projects; public: void set(int, char*, int); // functions overriding the void display_heading(); // base class definitions void display_projects(); }; /*----------------------Implementation of Class ---------------------*/ // member function definitions for 'employee' void employee::set(int c, char* s) { empno = c; strcpy(name, s); } void employee::display_heading() { cout << "Employee Information : \n"; } void employee::display() { cout << "Employee No. : " << empno << "\n"; cout << "Name : " << name << "\n"; } // member function definitions for 'manager' void manager::set(int c, char* s, int p) { no_of_projects = p; employee::set(c, s);// base class function explicitly invoked } void manager::display_heading() { cout << "Manager Details : \n"; } void manager::display_projects() { cout << "No of Projects currently handling : "; cout << no_of_projects << "\n"; 9.

(10) Prof.Manoj S.Kavedia (9860174297)([email protected]) } /*----------------------End of Class definitions ---------------*/ void main(void) { manager manoj; manoj.set(1000, "Manoj", 4); manoj.display_heading(); manoj.display(); manoj.display_projects(); } Explanation Class ‘employee’ has three public methods. — set(), display() and display_header(). It is a self sufficient class and can be used to generate objects. The second class ‘manager is derived from ‘employee’ using public inheritance. Also manager is an employee and hence need to have all the attributes of the ‘employee’ class. But it also want to have one additional attribute ‘no_of_projects’ it is currently handling. The inheritance is a good idea here to get the functionality of ‘employee’ accessible through manager’. The only difference are, manager’s information contains, ‘name’, ‘empno’ and ‘no.of_projects’ which forced us to override function set() which initialises its own field ‘no_of_projects’ and invokes the set() function for the base class passing the remaining two parameters. Another way to the overriding. The origin functionality thus can be invoked from a new overriding definition, only thing is you explicitly need to give the base class name and the scope resolution operator; otherwise it will become the recursive call with one less parameter which leads to compilation error. The second function which is overridden by manager’ is ‘display()‘. We want here to display ‘manager details” instead of a general heading for all employee. “Employee information”. This new definition need not invoke the original definition as we want only the new message to be printed and not the old one. The third base function display()’ is not overridden and hence get inherited to the ‘manager’ class directly. Thus for the object of type manager’ four method are available —‘set( )‘, ‘display( )‘, ‘display_header( )‘, ‘display_projects( )‘. Virtual Function Q11. What are Virtual Functions? Ans.Virtual, as the name implies, is something that exists in effect but not in reality. The concept of virtual function is the same as a function, but it does not really exist although it appears in needed places in a program. The object-oriented programming language C++ implements the concept of virtual function as a simple member function, like all member functions of the class. A virtual function is a member function of the base class and which is redefined by the derived class. When a derived class inherits the class containing the virtual function, it has ability to redefine the virtual functions. A virtual function has a different functionality in the derived class. The virtual function within the base class provides the 10.

(11) Prof.Manoj S.Kavedia (9860174297)([email protected]) form of the interface to the function. Virtual function implements the philosophy of one interface and multiple methods. The virtual functions are resolved at the run time. This is called dynamic binding. The functions which are not virtual are resolved at compile time which is called static binding. A virtual function is created using the keyword virtual which precedes the name of the function. Virtual functions are accessed using a base class pointer. A pointer to the base class can be created. A base class pointer can contain the address of the derived object as the derived object contains the subset of base class object. Every derived class is also a base class. When a base class pointer contains the address of the derived class object, at runtime it is decided which version of virtual function is called depending on the type of object contained by the pointer.. Q12.Describe what do you mean by virtual function Ans. A virtual function is one that does not really exist but it appears real in some parts of a program. Virtual functions are advanced features of the object oriented programming concept and they are not necessary for each C++ program. The polymorphic features can also be incorporated using the virtual functions. Although a base pointer can be made point to any number of derived object. It cannot directly access the members defined by the derived class. Polymorphism refers to the property by which objects belonging to objects are able to respond to the same message. But in different forms. Therefore it is essential to refer to the objects irrespective of their classes. This necessiates the use of single pointer to refer to the object of different derived classes. To achieve this we need virtual functions. When we use the same function name with same prototype in both base & derived classes. The function in the base class is declared as virtual. Syntax is Virtual return type function_Name(arg); When a function is made virtual C++ determines function call at run time based on the type of objects pointed by a base pointer rather than to the type of pointer. Thus we can execute different versions of functions declaring it virtual in the base class.. 11.

(12) Prof.Manoj S.Kavedia (9860174297)([email protected]) Example of Virtual Function /* Program to Illustrates Virtual Function */ #include<iostream.h> #include<conio.h> class Base { public : void display( ) { cout<<"\n Display Base "; } virtual void show( ) { cout<<"\n Show Base "; } }; class Derived : public Base { public : void display( ) { cout<<"\n Display Derived "; } void show( ) { cout<<"\n Show Derived "; } }; void main( ) { Base B; Derived D; Base *bptr; cout<<"\n bptr points to Base "; bptr = &B; bptr -> display( ); //calls Base version bptr -> show( ); // calls Base version cout<<" \n\n bptr points to Derived "; bptr = &D; bptr -> display( ); //calls Base version bptr -> show( ); // calls Derived version getch( ); } 12.

(13) Prof.Manoj S.Kavedia (9860174297)([email protected]) Output Bptr point to base class Display Base Show Base Bptr point to derived class Display Base Show Dervied Explanation In the example when bptr is made to point to the object D. the statement bptr –>display(); calls only the function associated with the Base (Base :: Display( )), whereas the statement bptr->show() calls the Derived version of show(). This is because the function display() has in not virtual in the Base class. Note : We must access the virtual function through the use of a pointer declared as a pointer to the base class.Run time polymorphism is achieved only when a virtual function is accessed through a pointer to base class. Q13.How does a Virtual Function work? Ans.Whenever a program has a virtual function declared, a v - table is constructed for the class. The v-table consists of addresses to the virtual functions for classes that contain one or more virtual functions. The object of the class containing the virtual function contains a virtual pointer that points to the base address of the virtual table in memory. Whenever there is a virtual function call, the v-table is used to resolve to the function address. An object of the class that contains one or more virtual functions contains a virtual pointer called the vptr at the very beginning of the object in the memory. Hence the size of the object in this case increases by the size of the pointer. This vptr contains the base address of the virtual table in memory. Note that virtual tables are class specific, i.e., there is only one virtual table for a class irrespective of the number of virtual functions it contains. This virtual table in turn contains the base addresses of one or more virtual functions of the class. At the time when a virtual function is called on an object, the vptr of that object provides the base address of the virtual table for that class in memory. This table is used to resolve the function call as it contains the addresses of all the virtual functions of that class. This is how dynamic binding is resolved during a virtual function call. The following code shows how we can write a virtual function in C++ and then use the same to achieve dynamic or runtime polymorphism. #include <iostream.h> class base { public: virtual void display() { 13.

(14) Prof.Manoj S.Kavedia (9860174297)([email protected]) cout<<”\nBase”; } }; class derived : public base { public: void display() { cout<<”\nDerived”; } }; void main() { base *ptr = new derived(); ptr->display(); } In the above example, the pointer is of type base but it points to the derived class object. The method display() is virtual in nature. Hence in order to resolve the virtual method call, the context of the pointer is considered, i.e., the display method of thederived class is called and not that of the base. If the method was non virtual in nature, the display() method of the base class would have been called. Q14.Describe Virtual Constructors and Destructors Ans.A constructor cannot be virtual because at the time when the constructor is invoked the virtual table would not be available in the memory. Hence we cannot have a virtual constructor. A virtual destructor is one that is declared as virtual in the base class and is used to ensure that destructors are called in the proper order. It is to be remembered that destructors are called in the reverse order of inheritance. If abase class pointer points to a derived class object and we some time later use the delete operator to delete the object, then the derived class destructor is not called. Refer to the code that follows: #include <iostream.h> class base { public: ~base() { } }; class derived : public base { public: ~derived() { 14.

(15) Prof.Manoj S.Kavedia (9860174297)([email protected]) } }; void main() { base *ptr = new derived(); // some code delete ptr; } In this case the type of the pointer would be considered. Hence as the pointer is of type base, the base class destructor would be called but the derived class destructor would not be called at all. The result is memory leak. In order to avoid this, we have to make the destructor virtual in thebase class. This is shown in the example below: #include <iostream.h> class base { public: virtual ~base() { } }; class derived : public base { public: ~derived() { } }; void main() { base *ptr = new derived(); // some code delete ptr; } Conclusion Virtual methods should be used judiciously as they are slow due to the overhead involved in searching the virtual table. They also increase the size of an object of a class by the size of a pointer. The size of a pointer depends on the size of an integer. Note that 15.

(16) Prof.Manoj S.Kavedia (9860174297)([email protected]) in DOS based systems the size of a pointer is 2 bytes whereas in UNIX based systems it is 4 bytes. Q15.List the properties if Virtual Functions Ans. Properties of Virtual Functions: • Dynamic Binding Property: Virtual Functions are resolved during run-time or dynamic binding. Virtual functions are also simple member functions. The main difference between a non-virtual C++ member function and a virtual member function is in the way they are both resolved. A non-virtual C++ member function is resolved during compile time or static binding. Virtual Functions are resolved during run-time or dynamic binding • • •. Virtual functions are member functions of a class. Virtual functions are declared with the keyword virtual. Virtual function takes a different functionality in the derived class.. Q16.List the rules for virtual function Ans. Rules For Virtual Functions Virtual functions are created for late binding some basic rules must be satisfied for the complier requirement.  Virtual function must be member of a class.  They cannot be static members.  They are accessed by using object pointer.  Virtual function can be friend of another class.  Virtual function in a base class must be defined even though it may not be used.  The prototype of class of version of virtual function & all derived class versions must be identical. I.e. its prototype should be same. If two function with same name have different prototype C++ will be considered as overloading & virtual keyword is ignored.  We cannot have virtual constructor but we can have virtual destructors are possible.  While the base pointer can point to any point of derived object than the reverse is not true.  When a base pointer points to a derived class, incrementing or decrementing will not make point to the next object of derived class but instead it is related to its base type.  If a virtual function is defined in the base class it is not necessary to redefined in the derived class, in such case it will invoke the base class function. Pure Virtual Function Q17.Describe what is pure virtual function Ans.Virtual function inside the main class must be declared to achieve polymorphism and redefined it in the derived class. The function inside the base class is seldom(rarely) used for performing any task. It only serves as a placeholder. Pure Virtual Function is a Virtual function with no body. 16.

(17) Prof.Manoj S.Kavedia (9860174297)([email protected]) Declaration of Pure Virtual Function: Since pure virtual function has no body, the programmer must add the notation =0 for declaration of the pure virtual function in the base class. class classname //This denotes the base class of C++ virtual function { public: //This denotes the pure virtual function in C++ virtual void virtualfunctioname() = 0 }; Example : if we have not defined any object of class shape the function draw in the base class must be defined as empty. Such functions are called do nothing function which may be defined as followsclass shape { protected: int d1,d2; public: virtual void draw()=0; } such functions are called pure virtual functions. Pure virtual function is a function declared in the base class that has no definition to the base class. In such cases the compiler requires each derived class to either define the function or redeclare it as a pure virtual function. The class containing pure virtual function can’t be used to declare any object of its own such classes are called as Abstract Base Class Example of Pure Virtual Function To understand the declaration and usage of Pure Virtual Function, refer to this example: class PureVirtual { public: virtual void example()=0; //Denotes pure virtual Function Definition }; class Exf1:public PureVirtual { public: void example() { cout<<"Manoj"; } }; class Exf2:public PureVirtual { public: void example() 17.

(18) Prof.Manoj S.Kavedia (9860174297)([email protected]) { cout<<"kavedia"; } }; void main() { PureVirtual * arra[2]; Exf1 e1; Exf2 e2; arra[0]=&e1; arra[1]=&e2; arra[0]->example(); arra[1]->example(); } Explanation Since the above example has no body, the pure virtual function example() is declared with notation =0 in the base class PureVirtual. The two derived class named Exf1 and Exf2 are derived from the base class PureVirtual. The pure virtual function example() takes up new definition. In the main function, a list of pointers is defined to the base class. Two objects named e1 and e2 are defined for derived classes Exf1 and Exf2. The address of the objects e1 and e2 are stored in the array pointers which are then used for accessing the pure virtual function example() belonging to both the derived class EXf1 and EXf2 and thus, the output is as in the above example. The programmer must clearly understand the concept of pure virtual functions having no body in the base class and the notation =0 is independent of value assignment. The notation =0 simply indicates the Virtual function is a pure virtual function as it has no body. Some programmers might want to remove this pure virtual function from the base class as it has no body but this would result in an error. Without the declaration of the pure virtual function in the base class, accessing statements of the pure virtual function such as, arra[0]->example() and arra[1]->example() would result in an error. The pointers should point to the base class PureVirtual. Special care must be taken not to remove the statement of declaration of the pure virtual function in the base class . Program asked in board exams Example-1 Write any program which shows compile time polymorphism using function overloading Ans. #include<iostream> using namespace std; class employee { public: 18.

(19) Prof.Manoj S.Kavedia (9860174297)([email protected]) int week; int year; double calculate(double salary) { return(salary*week); } int calculate(int salary) { return(salary*week*year); } employee(int week1) { week=week1; } employee(int week1,int year1) { week=week1; year=year1; } }; int main() { int sal; double sal2; employee emp1(10); employee emp2(10,3); cout << "Enter the no years for first employee" << endl; cin >> emp1.year; cout << endl << "Enter the salary per week for first employee" << endl; cin >> sal; cout << "The total salary of first employee is : " << emp1.calculate(sal) << endl; cout << endl << "Enter the salary per week for second employee is : " << endl; cin >> sal2; cout << "The total salary of second employee is for one year: " << emp2.calculate(sal2) << endl; return(0); } Explanation In the program function calculate() and constructor of class employee are overloaded. The function calculate() is declared two times but with different parameter 19.

(20) Prof.Manoj S.Kavedia (9860174297)([email protected]) type and same with constructor employee which is also declared two times but with different parameter types. The following statements double calculate(double salary) { return(salary*week); } int calculate(int salary) { return(salary*week*year); } declare functions with same name calculate but one has parameter type integer and other has parameter type double. The function calculate() is overloaded. The statements employee(int week1) { week=week1; } employee(int week1,int year1) { week=week1; year=year1; } declare two constructors of class employee where one constructor’s parameter list is different from other constructor’s parameter list. The constructor is overloaded. Example -2 Write program demonstrating static binding Ans. //demonstration of static binding #include <iostream.h> class square { protected: int X; public void getdata(); void display(); int area() }; class rectangle : public square { protected: int y; public void getdata(); 20.

(21) Prof.Manoj S.Kavedia (9860174297)([email protected]) void display(); int areaC;. I. }; void square:: getdata() { cout << “ enter the value of side x ? \n”; cin >>X; } void square:: disp() { cout<< “value of x = y = “ << X << endl; cout << “ Area of the square = “ << area(); cout << endl; } int square :: area() { int temp = X*X; return(temp); } void rectangle :: getdata() { cout << “ enter the value of sides x and y ? \n”; Cin >> X >>y; } void rectangle:: display() { cout <<“value of <<x<< “ and y=”; cout << y << endl; cout << Area of the rectangle” << area(); cout << endl; } int rectangle :: area() { int temp = X*y; return(temp); } void main() { square sqobj; rectangle rectobj; square *ptr; ptr = &sqobj; ptr = &rectobj; ptr->getdata() ; ptr->area(); ptr->display(); } 21.

(22) Prof.Manoj S.Kavedia (9860174297)([email protected]) Output enter the of side x? 10 value of x= y = 10 Area of the square = 100 Explanation The derived class rectangle is inherited from the base class square through public derivation. It is known that an object of a derived class not only inherits characteristics from the base class but also has characteristics that are specific to the derived class. Example-3 Q.Write program to demonstrate virtual function Ans. include<iostream> using namespace std; class shape { public: int side; virtual int volume() { cout << endl <<"Virtual function of base class " << endl; return(0); } }; class cube: public shape { public: int volume() { cout << endl << "Volume function of cube " << endl; return(side*side*side); } }; class cuboid:public shape { public: int breadth; int height; int volume() { cout << endl << "Volume function of cuboid " << endl; 22.

(23) Prof.Manoj S.Kavedia (9860174297)([email protected]) return(side*breadth*height); } }; int main() { shape *s,s1; cube c1; cuboid c2; cout << "Enter the side of the cube" << endl; cin >> c1.side; cout << endl << "Enter the side of the cuboid " << endl; cin >> c2.side; cout << endl << "Enter the breadth of the cuboid" << endl; cin >> c2.breadth; cout << endl << "Enter the height of the cuboid" << endl; cin >> c2.height; s=&s1; s->volume(); s=&c1; cout << endl << "The volume of the cube " << s->volume() << endl; s=&c2; cout << endl << "The volume of the cuboid " << s->volume() << endl; return(0); } Explanation `The program has base class shape and class cube and cuboid which inherits base class. The base class has virtual function volume. The statements virtual int volume() { cout << endl <<"Virtual function of base class " << endl; return(0); } define the member function volume() of base class. The function is virtual. The keyword virtual precedes the function return type. In the following statements int volume() { cout << endl << "Volume function of cube " << endl; return(side*side*side); } the derived class cube which inherits base class shape, redefines the function volume() which is virtual. In the following statements 23.

(24) Prof.Manoj S.Kavedia (9860174297)([email protected]) int volume() { cout << endl << "Volume function of cuboid " << endl; return(side*breadth*height); } the derived class cuboid which inherits the base class shape, redefines the function volume(). The statement shape *s,s1; declares a pointer to the base class shape. The statement s=&s1; pointer s contains the address of the base class object s1. The statement s->volume(); calls the function volume of the base class shape as the pointer contains the address of the base class object. The statement s=&c1; pointer s now contains the address of the derived class object c1. The statement cout << endl << "The volume of the cube " << s->volume() << endl; displays the volume of the cube as s->volume() calls the function volume of the derived class cube. The pointer s contains the address of the object of derived class cube. In the statement s=&c2; pointer s now contains the address of the derived class object c2. The statement cout << endl << "The volume of the cuboid " << s->volume() << endl; displays the volume of the cuboid as s->volume() calls the function volume of the derived class cuboid. The pointer s now contains the address of the object of derived class cuboid. When a virtual function is not defined by the derived class, the version of the virtual function defined by the base class is called. When a derived class which contains the virtual function is inherited by another class, virtual function can be overloaded for the new derived class. This means that virtual function can be inherited. Board Question year Wise 24.

(25) Prof.Manoj S.Kavedia (9860174297)([email protected]) Winter 2007 a. What is difference between compile-time polymorphism and run-time polymorphism ? b. Illustrate use of virtual function with suitable example Summer 2008 a. Define virtual function with its syntax b. What do you mean by polymorphism? state two types of polymorphism c. Write any program which shows compile time polymorphism using function overloading d. What is runtime polymorphism?Explain with suitable example Winter 2008 a. Define polymorphism. Give example b. Can base class pointer be used to call virtual function? Justify your answers. c. Explain the static binding with example. Summer 2009 a. List the types of polymorphism b. List any four rules for creating virtual functions c. Write program demonstrating static binding. d. Explain the static binding with example. Winter 2009 a. Define static and dynamic binding. b. Define polymorphism. Enlist its types. c. What is virtual function? Why do we need virtual function? d. What is static and dynamic polymorphism? How to achieve it? e. Write rules of virtual function. Summer 2010 a. Define polymorphism. List types of polymorphism. b. What is pure virtual function? c. What is static and dynamic polymorphism? How to achieve it d. Polymorphism is implemented using function overloading. Justify the statement. 25.

(26)

References

Related documents

If the aviator suddenly increases the angle of attack of the wings to almost the critical angle, by moving the ‘stick’ back to that position, they will generate a

- If we want an object to look in the function table for the constructed class, not the variable type (often a base type) we make the function “virtual”. ▪a non-virtual method call

Low Cost / Low Control • Profitability • Compliance • Theft / Loss • Financial Reporting • Customer Service Sweet spot. What Condition is Your Inventory

¾An abstract class can be used to declare pointers that can access objects derived from the abstract base class. Object Oriented Programming

The genomic features enriched in CNVs (homologous regions, masked regions, CpG sites, TSSs and AT-rich intervals) support specific mechanisms of the formation of CNVs.. Moreover,

Such interpretations of Daoism, which have become prevalent in contemporary Western philosophical approaches, are opposed to Chinese commentarial transmissions as well as

The key to applying the External Polymorphism pattern is to define an abstract base class called Dumpable that con- tains a pure virtual dump method:...

If we declare say function f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type