UNIT 5CONSTRUCTORS AND DESTRUCTORS 100 Structure 5.0 LearningObjectives 5.1 Introduction 5.2 Need for Constructor and Destructor 5.2.1. Constructor 5.2.2. Destructor 5.3 Type of constructor 5.3.1 Default constructor 5.3.2 Parameterized constructor 5.3.3 Copy constructor 5.4 Destructors 5.5 Summary 5.6 KeyWords/Abbreviations 5.7 LearningActivity 5.8 Unit End Questions (MCQ andDescriptive) 5.9 References 5.0 LEARNINGOBJECTIVES After studying this unit, you will be able to: Recognize the need for constructor and destructors Describe the copy constructor Explain the dynamic constructor CU IDOL SELF LEARNING MATERIAL (SLM)
Discuss the destructors 5.1 INTRODUCTION When an object is created all the members of the object are allocated memory spaces. Each object has its individual copy of member variables. However the data members are not initialized automatically. If left uninitialized these members contain garbage values. Therefore it is important that the data members are initialized to meaningful values at the time of object creation. Conventional methods of initializing data members have lot of limitations. In this unit you will learn alternative and more elegant ways initializing data members to initial values. When a C++ program runs it invariably creates certain objects in the memory and when the program exits the objects must be destroyed so that the memory could be reclaimed for further use. C++ provides mechanisms to cater to the above two necessary activities through constructors and destructors methods. 5.2 NEED FOR CONSTRUCTOR AND DESTRUCTOR 5.2.1 Constructor Constructor is public method that is called automatically when the object of a particular class is created. C++ provides a default constructor method to all the classes. This constructor method takes no parameters. Actually the default constructor method has been defined in system.object class. Since every class that you create is an extension of system.object class, this method is inherited by all the classes. The default constructor method is called automatically at the time of creation of an object and does nothing more than initializing the data variables of the object to valid initial values. While writing a constructor function the following points must be kept in mind: 1. The name of constructor method must be the same as the class name in which it is defined. 2. A constructor method must be a public method. 101 CU IDOL SELF LEARNING MATERIAL (SLM)
3. Constructor method does not return any value. 4. A constructor method may or may not have parameters. Let us examine a few classes for illustration purpose. The class abc as defined below does not have user defined constructor method. The main function above an object named myabc has been created which belongs to abc class defined above. Since class abc does not have any constructor method, the default constructor method of C++ will be called which will initialize the member variables as: Let us now redefine myabc class and incorporate an explicit constructor method as shown below: The main function above an object named myabc has been created which belongs to abc class defined above. Since class abc does not have any constructor method, the default constructor method of C++ will be called which will initialize the member variables as: 102 CU IDOL SELF LEARNING MATERIAL (SLM)
Let us now redefine myabc class and incorporate an explicit constructor method as shown below: Observed that myabc class has now a constructor defined to except two parameters of integer type. We can now create an object of myabc class passing two integer values for its construction, as listed below: In the main function myabc object is created value 100 is stored in data variable x and 200 is stored in data variable y. There is another way of creating an object as shown below. 103 CU IDOL SELF LEARNING MATERIAL (SLM)
Both the syntaxes for creating the class are identical in effect. The choice is left to the programmer. There are other possibilities as well. Consider the following class differentials: In this class constructor has been defined to have no parameter. When an object of this class is created the programmer does not have to pass any parameter and yet the data variables x, yis initialized to 100 and 200 respectively. Finally, look at the class differentials as given below: 104 CU IDOL SELF LEARNING MATERIAL (SLM)
Class myabc has three constructors having no parameter, one parameter and two parameters respectively. When an object to this class is created depending on number of parameters one of these constructors is selected and is automatically executed. 105 CU IDOL SELF LEARNING MATERIAL (SLM)
5.2.2 Destructor When a program no longer needs an instantiated object it destroys it. If you do not supply a destructor function, C++ supplies a default destructor for you, unknown to you. The program uses the destructor to destroy the object for you. When should you define your own destructor function? In many cases you do not need a destructor function. However, if your class created dynamic objects, then you need to define your own destructor in which you will delete the dynamic objects. This is because dynamic objects cannot be deleted on their own. So, when the object is destroyed, the dynamic objects are deleted by the destructor function you define.The destructor will get called again at the close } of the block in which the local was created. This is a guarantee of the language; it happens automatically; there’s no way to stop it from happening. But you can get really bad results from calling a destructor on the same object a second time! Bang! You’re dead! A destructor function has the same name as the class, and does not have a returned value. However you must precede the destructor with the tilde sign, which is ~ . The following code illustrates the use of a destructor against dynamic objects: 106 CU IDOL SELF LEARNING MATERIAL (SLM)
The destructor function is automatically called, without you knowing, when the program no longer needs the object. If you defined a destructor function as in the above code, it will be executed. If you did not define a destructor function, C++ supplies you one, which the program uses unknown to you. However, this default destructor will not destroy dynamic objects. 107 CU IDOL SELF LEARNING MATERIAL (SLM)
5.3 TYPE OF CONSTRUCTOR 5.3.1Default constructor If no constructor is defined in the class then the compiler automatically creates one for the program. This constructor which is created by the compiler when there is no user defined constructor and which doesn’t take any parameters is called default constructor. Format of default constructor /*.....format of default constructor..........*/ class class_name { ......... public: class_name() { }; //default constructor ......... }; 5.5.2 Parameterized Constructor To put it up simply, the constructor that can take arguments are called parameterized constructor. In practical programs, we often need to initialize the various data elements of the different object with different values when they are created. This can be achieved by passing the arguments to the constructor functions when the object is created. Following sample program will highlight the concept of parameterized constructor /*.....A program to find area of rectangle .......... */ 108 CU IDOL SELF LEARNING MATERIAL (SLM)
#include<iostream> using namespace std; class ABC { private: int length,breadth,x; public: ABC (int a,int b) //parameterized constructor to initialize l and b { length = a; breadth = b; } int area( ) //function to find area { x = length * breadth; return x; } void display( ) //function to display the area { cout << \"Area = \" << x << endl; 109 CU IDOL SELF LEARNING MATERIAL (SLM)
} }; int main() { ABC c(2,4); //initializing the data members of object 'c' implicitly c.area(); c.display(); ABC c1= ABC(4,4); // initializing the data members of object 'c' explicitly c1.area(); c1.display(); return 0; } //end of program Output Area = 8 Area = 16 Note: Remember that constructor is always defined and declared in public section of the class and we can’t refer to their addresses 5.3.3 Copy Constructor 110 CU IDOL SELF LEARNING MATERIAL (SLM)
Generally in a constructor the object of its own class can’t be passed as a value parameter. But the classes own object can be passed as a reference parameter. Such constructor having reference to the object of its own class is known as copy constructor. Moreover, it creates a new object as a copy of an existing object. For the classes which do not have a copy constructor defined by the user, compiler itself creates a copy constructor for each class known as default copy constructor. Example to illustrate the concept of copy constructor /*.....A program to highlight the concept of copy constructor.......... */ #include<iostream> using namespace std; class example { private: int x; public: example (int a) //parameterized constructor to initialize l and b { x = a; } example( example &b) //copy constructor with reference object argument 111 CU IDOL SELF LEARNING MATERIAL (SLM)
{ x = b.x; } int display( ) //function to display { return x; } }; int main() { example c1(2); //initializing the data members of object 'c' implicitly example c2(c1); //copy constructor called example c3 = c1; example c4 = c2; cout << \"example c1 = \" << c1.display() << endl; cout << \"example c2 = \" << c2.display() << endl; cout << \"example c3 = \" << c3.display() << endl; cout << \"example c4 = \" << c4.display() << endl; return 0; 112 CU IDOL SELF LEARNING MATERIAL (SLM)
} //end of program Output example c1 = 2 example c2 = 2 example c3 = 2 example c4 = 2 Note: In copy constructor passing an argument by value is not possible. 5.4 DESTRUCTORS Constructors create an object, allocate memory space to the data members and initialize the data members to appropriate values; at the time of object creation. Another member method called destructor does just the opposite when the program creating an object exits, thereby freeing the memory. A destructive method has the following characteristics: 1. Name of the destructor method is the same as the name of the class preceded by a tilde(~). 2. The destructor method does not take any argument. 3. It does not return any value The following codes snippet shows the class abc with the destructor method; 113 CU IDOL SELF LEARNING MATERIAL (SLM)
Whenever an object goes out of the scope of the method that created it, its destructor method is invoked automatically. However if the object was created using new operator, the destructor must be called explicitly using delete operator. The syntax of delete operator is as follows: delete(object); In reverse order of construction: First constructed, last destructed. In the following example, the order for destructors will be a[9], a[8], ..., a[1], a[0]: 5.5SUMMARY A constructor is a member function of a class, having the same name as its class and which is called automatically each time an object of that class it created. 114 CU IDOL SELF LEARNING MATERIAL (SLM)
It is used for initializing the member variables with desired initial values. A variable (including structure and array type) in C++ may be initialized with a value at the time of its declaration. The responsibility of initialization may be shifted, however, to the compiler by including a member function called constructor. A class constructor, if defined, is called whenever a program created an object of that class. Constructors are public member unless otherwise there is a good reason against. A constructor may take argument (s). A constructor may taking no argument(s) is known as default constructor. A constructor may also have parameter (s) or argument (s), which can be provided at the time of creating an object of that class. C++ classes are derived data types and so they have constructor (s). Copy constructor is called whenever an instance of same type is assigned to another instance of the same class. If a constructor is called with less number of arguments than required an error occurs. Every time an object is created its constructor is invoked. The functions that is automatically called when an object is no more required is known as destructor. It is also a member function very much like constructors but with an opposite intent. We may set the default value for the constructor parameter. A class destructor is a class method having the same name as the class name and is prefixed with tilde (~) sign. The destructor does not return anything and does not accept any argument. A class definition may contain one and only one destructor. 115 CU IDOL SELF LEARNING MATERIAL (SLM)
5.6 KEY WORDS/ABBREVIATIONS Constructor: A member function having the same name as its class and that initializes class objects with legal initial values. Copy Constructor: A constructor that initializes an object with the data values of another object. Default Constructor: A constructor that takes no arguments. Destructor: A member function having the same name as its class but preceded by ~ sign and that deinitializes an object before it goes out of scope. Friend Function: A function which is not a member of a class but which is given special permission Notes to access private and protected members of the class. Static Member Functions: Functions that can access only the static members. Temporary Object: An anonymous short lived obj 5.7LEARNINGACTIVITY 1.Write C++ program by taking a \"patient\" class and by using constructor and destructor __________________________________________________________________________ __________________________________________________________________________ 2. Write a program to calculate factorial of a given number using copy constructor. __________________________________________________________________________ __________________________________________________________________________ 5.8 UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE) 116 CU IDOL SELF LEARNING MATERIAL (SLM)
A. Descriptive Types Questions 1. Can one constructor of a class call another constructor of the same class to initialize the this object? Justify your answers with an example. 2. Should my constructors use “initialization lists” or “assignment”? Discuss. 3. Spot out the error in the following code and correct it. 4. How is a copy constructor different from a constructor? Illustrate with suitable examples 5. Identify and give the specific program for a constructor without parameters B. Multiple Choice Questions 117 1. What is the role of a constructor in classes? (a) To modify the data whenever required (b) To destroy an object (c) To initialize the data members of an object when it is created CU IDOL SELF LEARNING MATERIAL (SLM)
(d) To call private functions from the outer world 2. Why constructors are efficient instead of a function init() defined by the user to initialize the data members of an object? (a) Because user may forget to call init() using that object leading segmentation fault (b) Because user may call init() more than once which leads to overwriting values (c) Because user may forget to define init() function (d) All of the mentioned 3. What is a copy constructor? (a) A constructor that allows a user to move data from one object to another (b) A constructor to initialize an object with the values of another object (c) A constructor to check the whether to objects are equal or not (d) A constructor to kill other copies of a given object. 4. What happens if a user forgets to define a constructor inside a class? (a) Error occurs (b) Segmentation fault (c) Objects are not created properly (d) Compiler provides a default constructor to avoid faults/errors 5. How many parameters does a default constructor require? (a) 1 (b) 2 (c) 0 (d) 3 Answers 118 1. (c), 2. (d), 3. (b), 4. (d), 5. (c) CU IDOL SELF LEARNING MATERIAL (SLM)
5.9REFERENCES Er V. K. Jain, Object Oriented Programming with C++, Cyber Tech Publication, Daryaganj N Delhi-110002 Bjarne AT&T Labs Murray Hill, New Jersey Stroustrup, Basics of C++ Programming, Special Edition, Publisher: Addison-Wesley Professional. C/C++ Programming manual – By Tim Lin and Saeed Monemi http://www.cprogramming.com/tutorial/constructor_destructor_ordering.html http://publib.boulder.ibm.com/infocenter/comphelp/v8v101 index.jsp?topic= %2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr374.htm http://www.codezclub.com/cpp-solved-programs-problems-solutions/c-constructor- destructor-solved-programs-solutions/ Constructing constructors by Kent Reisdorph and Jody Hagins February 1999 C++ Tutorial - Constructor - 2016 Golden Gate Ave, San Francisco 119 CU IDOL SELF LEARNING MATERIAL (SLM)
UNIT6 INHERITANCE 120 Structure 6.0 LearningObjectives 6.1 Introduction 6.2 Defining Derived Class 6.3 Modes of Inheritance 6.3.1 Single Inheritance 6.3.2 Multilevel Inheritance 6.3.3 Multiple Inheritance 6.3.4 Hierarchical Inheritance CU IDOL SELF LEARNING MATERIAL (SLM)
6.3.5 Hybrid Inheritance 121 6.4 Ambiguity in Multiple and Multipath Inheritance 6.4.1Ambiguity in Multiple Inheritance 6.4.2Ambiguity in Multipath Inheritance 6.5 Virtual base class 6.6 Overriding Member Function 6.7 Member Classes: Nesting of Classes 6.8 Summary 6.9 KeyWords/Abbreviations 6.10 LearningActivity 6.11 Unit End Questions (MCQ andDescriptive) 6.12 References 6.0 LEARNINGOBJECTIVES After studying this unit, you will be able to: Recognize the inheritance Describe the different types of inheritance Explain the ambiguity in multiple and multipath inheritance Discuss the virtual base class Identify the overriding member function. 6.1 INTRODUCTION CU IDOL SELF LEARNING MATERIAL (SLM)
Reusability of code is a characteristic feature of OOP. C++ strongly supports the concept of reusability. The C++ classes can be used again in several ways. Once a class has been written andtested, it can be adopted by other programmers. New classes can be defined reusing the properties Notes of existing ones. The mechanism of deriving a new class from an old one is called ‘INHERITANCE’. This is often referred to as ‘IS-A’ relationship because every object of the class being defined “is” also an object of inherited class type. The old class is called ‘BASE’ class and the new one is called ‘DERIVED’ class or sub- class. 6.2DEFINING DERIVED CLASS A derived class is specified by defining its relationship with the base class in addition to its own details. The general syntax of defining a derived class is as follows: The colon (:) indicates that the derivedclassname class is derived from the baseclassname class. The access_specifier or the visibility mode is optional and, if present, may be public, private or protected. By default it is private. Visibility mode describes the accessibility status of derived features. For example, 122 CU IDOL SELF LEARNING MATERIAL (SLM)
In inheritance, some of the base class data elements and member functions are inherited into the derived class and some are not. We can add our own data and member functions and thus extend the functionality of the base class. 6.3 FORMS OF INHERITANCE 6.3.1 Single Inheritance When a class inherits from a single base class, it is referred to as single inheritance. Following program shows single inheritance using public derivation 123 CU IDOL SELF LEARNING MATERIAL (SLM)
6.3.2 Multiple Inheritance A class can inherit the attributes of two or more classes. This mechanism is known as ‘MULTIPLE INHERITANCE’. Multiple inheritance allows us to combine the features of several existing classes as a starting point for defining new classes. The syntax of the derived class is as follows: 124 CU IDOL SELF LEARNING MATERIAL (SLM)
6.1 Multiple Inheritance Where the visibility refers to the access specifiers i.e. public, private or protected. Following program shows the multiple inheritance. We present the below program to demonstrate Multiple Inheritance. #include <iostream> usingnamespacestd; //multiple inheritance example classstudent_marks { protected: introllNo, marks1, marks2; public: voidget() { cout << \"Enter the Roll No.: \"; cin >> rollNo; 125 CU IDOL SELF LEARNING MATERIAL (SLM)
cout << \"Enter the two highest marks: \"; cin >> marks1 >> marks2; } }; classcocurricular_marks { protected: intcomarks; public: voidgetsm() { cout << \"Enter the mark for CoCurricular Activities: \"; cin >> comarks; } }; //Result is a combination of subject_marks and cocurricular activities marks classResult : publicstudent_marks, publiccocurricular_marks { inttotal_marks, avg_marks; public: voiddisplay() { 126 CU IDOL SELF LEARNING MATERIAL (SLM)
total_marks = (marks1 + marks2 + comarks); 127 avg_marks = total_marks / 3; cout << \"\\nRoll No: \"<< rollNo << \"\\nTotal marks: \"<< total_marks; cout << \"\\nAverage marks: \"<< avg_marks; } }; intmain() { Result res; res.get(); //read subject marks res.getsm(); //read cocurricular activities marks res.display(); //display the total marks and average marks } Output: Enter the Roll No.: 25 Enter the two highest marks: 40 50 Enter the mark for CoCurricular Activities: 30 Roll No: 25 Total marks: 120 Average marks: 40 CU IDOL SELF LEARNING MATERIAL (SLM)
6.3.3 Multilevel Inheritance Multiple Inheritance is pictorially represented below. When the inheritance is such that, the class A serves as a base class for a derived class B which in turn serves as a base class for the derived class C. This type of inheritance is called ‘MULTILEVEL INHERITANCE’. The class B is known as the ‘INTERMEDIATE BASE CLASS’ since it provides a link for the inheritance between A and C. The chain ABC is called ‘INHERITANCE*PATH’ for e.g. Fig 6.2 Multilevel Inheritance 128 Let us see an example of Multilevel Inheritance. #include <iostream> #include <string> usingnamespacestd; classAnimal CU IDOL SELF LEARNING MATERIAL (SLM)
{ 129 string name=\"\"; public: inttail=1; intlegs=4; }; classDog : publicAnimal { public: voidvoiceAction() { cout<<\"Barks!!!\"; } }; classPuppy:publicDog{ public: voidweeping() { CU IDOL SELF LEARNING MATERIAL (SLM)
cout<<\"Weeps!!\"; } }; intmain() { Puppy puppy; cout<<\"Puppy has \"<<puppy.legs<<\" legs\"<<endl; cout<<\"Puppy has \"<<puppy.tail<<\" tail\"<<endl; cout<<\"Puppy \"; puppy.voiceAction(); cout<<\" Puppy \"; puppy.weeping(); } Output: Puppy has 4 legs Puppy has 1 tail Puppy Barks!!! Puppy Weeps!! Here we modified the example for Single inheritance such that there is a new class Puppy which inherits from the class Dog that in turn inherits from class Animal. We see that the class Puppy acquires and uses the properties and methods of both the classes above it. 6.3.4 Hierarchical Inheritance 130 CU IDOL SELF LEARNING MATERIAL (SLM)
Another interesting application of inheritance is to use is as a support to a hierarchical design of a class program. Many programming problems can be cast into a hierarchy where certain features of one level are shared by many others below that level for e.g. Fig 6.3 HierarchicalInheritance Example demonstrating Hierarchical Inheritance #include <iostream> usingnamespacestd; //hierarchical inheritance example classShape // shape class -> base class { public: intx,y; voidget_data(intn,intm) { 131 CU IDOL SELF LEARNING MATERIAL (SLM)
x= n; 132 y = m; } }; classRectangle : publicShape // inherit Shape class { public: intarea_rect() { intarea = x*y; returnarea; } }; classTriangle : publicShape // inherit Shape class { public: inttriangle_area() { floatarea = 0.5*x*y; returnarea; } CU IDOL SELF LEARNING MATERIAL (SLM)
}; 133 classSquare : publicShape // inherit Shape class { public: intsquare_area() { floatarea = 4*x; returnarea; } }; intmain() { Rectangle r; Triangle t; Square s; intlength,breadth,base,height,side; //area of a Rectangle std::cout << \"Enter the length and breadth of a rectangle: \"; cin>>length>>breadth; r.get_data(length,breadth); intrect_area = r.area_rect(); std::cout << \"Area of the rectangle = CU IDOL SELF LEARNING MATERIAL (SLM)
\"<<rect_area<< std::endl; 134 //area of a triangle std::cout << \"Enter the base and height of the triangle: \"; cin>>base>>height; t.get_data(base,height); floattri_area = t.triangle_area(); std::cout <<\"Area of the triangle = \"<< tri_area<<std::endl; //area of a Square std::cout << \"Enter the length of one side of the square: \"; cin>>side; s.get_data(side,side); intsq_area = s.square_area(); std::cout <<\"Area of the square = \"<< sq_area<<std::endl; return0; } Output: Enter the length and breadth of a rectangle: 10 5 Area of the rectangle = 50 Enter the base and height of the triangle: 4 8 Area of the triangle = 16 CU IDOL SELF LEARNING MATERIAL (SLM)
Enter the length of one side of the square: 5 Area of the square = 20 The above example is a classic example of class Shape. We have a base class Shape and three classes i.e. rectangle, triangle, and square are derived from it. We have a method to read data in the Shape class while each derived class has its own method to calculate area. In the main function, we read data for each object and then calculate the area. 6.3.5 Hybrid Inheritance There could be situations where we need to apply two or more types of inheritance to design a program. Basically Hybrid Inheritance is the combination of one or more types of the inheritance. Here is one implementation of hybrid inheritance. #include <iostream> 135 #include <string> usingnamespacestd; //Hybrid inheritance = multilevel + multilpe classstudent{ //First base Class intid; string name; public: voidgetstudent(){ cout << \"Enter student Id and student name\"; cin >> id >> name; CU IDOL SELF LEARNING MATERIAL (SLM)
} }; classmarks: publicstudent{ //derived from student protected: intmarks_math,marks_phy,marks_chem; public: voidgetmarks(){ cout << \"Enter 3 subject marks:\"; cin >>marks_math>>marks_phy>>marks_chem; } }; classsports{ protected: intspmarks; public: voidgetsports(){ cout << \"Enter sports marks:\"; cin >> spmarks; } }; 136 CU IDOL SELF LEARNING MATERIAL (SLM)
classresult : publicmarks, publicsports{//Derived class by multiple inheritance// inttotal_marks; floatavg_marks; public: voiddisplay(){ total_marks=marks_math+marks_phy+marks_chem; avg_marks=total_marks/3.0; cout << \"Total marks =\"<< total_marks << endl; cout << \"Average marks =\"<< avg_marks << endl; cout << \"Average + Sports marks =\"<< avg_marks+spmarks; } }; intmain(){ result res;//object// res.getstudent(); res.getmarks(); 137 CU IDOL SELF LEARNING MATERIAL (SLM)
res.getsports(); res.display(); return0; } Output: Enter student Id and student name 25 Ved Enter 3 subject marks:89 88 87 Enter sports marks:40 Total marks =264 Average marks =88 Average + Sports marks =128 Here we have four classes i.e. Student, Marks, Sports, and Result. Marks are derived from the student class. The class Result derives from Marks and Sports as we calculate the result from the subject marks as well as sports marks. The output is generated by creating an object of class Result that has acquired the properties of all the three classes. Note that in hybrid inheritance as well, the implementation may result in “Diamond Problem” which can be resolved using “virtual” keyword as mentioned previously. 6.4AMBIGUITY IN MULTIPLE AND MULTIPATH INHERITANCE 6.4.1 Ambiguity in Multiple Inheritance In multiple inheritances, there may be possibility that a class may inherit member functions with same name from two or more base classes and the derived class may not have functions with same name as those of its base classes. If the object of the derived class need to access one of the same named member function of the base classes then it result in ambiguity as it is not clear to the compiler which base’s class member function should be invoked. The 138 CU IDOL SELF LEARNING MATERIAL (SLM)
ambiguity simply means the state when the compiler confused. 139 Syntax: class a { private: ……………. public: void abc () {} ……………. ……………. }; class b { private: ……………. public: void abc() {} ……………. ……………. }; CU IDOL SELF LEARNING MATERIAL (SLM)
class c : public a , public b { private: ……………. public: ……………. ……………. }; void main() { c obj; obj.abc();//Error …………….. } In this example, the two base classes a and b have function of same name abc() which are inherited to the derived class c. When the object of the class c is created and call the function abc() then the compiler is confused which base’s class function is called by the compilerThe ambiguity can be resolved by using the scope resolution operator to specify the class in which the member function lies as given below: obj.a :: abc(); This statement invoke the function name abc() which are lies in base class a. 6.4.2 Ambiguity in Multipath Inheritance 140 CU IDOL SELF LEARNING MATERIAL (SLM)
Sometimes we need to apply two or more types of inheritance to design a program and this type of inheritance are called hybrid inheritance. But in hybrid inheritance, if multiple paths exit between a base class and derived class through different intermediate classes, then derived class inherits the members of the base class more than one time and it results in ambiguity. Here, base class is called indirect base class and intermediate base classes are called direct base classes. To avoid this ambiguity, the indirect base class is made virtual base class and to define base class as virtual, a keyword virtual is appended when extending the direct base classes from the indirect base class as given in the example. In this way, when we define the indirect base class virtual, compiler take care that only one copy of that class is inherited, regardless of how many inherited paths exist between the virtual base class and the derived class. Fig 6.4 Hybrid inheritance 141 #include <iostream> #include <conio> using namespace std; class person { public: CU IDOL SELF LEARNING MATERIAL (SLM)
char name[100]; 142 int code; void input() { cout<<\"\\nEnter the name of the person : \"; cin>>name; cout<<endl<<\"Enter the code of the person : \"; cin>>code; } void display() { cout<<endl<<\"Name of the person : \"<<name; cout<<endl<<\"Code of the person : \"<<code; } }; class account:virtual public person { public: float pay; void getpay() CU IDOL SELF LEARNING MATERIAL (SLM)
{ 143 cout<<endl<<\"Enter the pay : \"; cin>>pay; } void display() { cout<<endl<<\"Pay : \"<<pay; } }; class admin:virtual public person { public: int experience; void getexp() { cout<<endl<<\"Enter the experience : \"; cin>>experience } void display() CU IDOL SELF LEARNING MATERIAL (SLM)
{ 144 cout<<endl<<\"Experience : \"<<experience; } }; class master:public account,public admin { public: char n[100]; void gettotal() { cout<<endl<<\"Enter the company name : \"; cin>>n; } void display() { cout<<endl<<\"Company name : \"<<n; } }; int main() { CU IDOL SELF LEARNING MATERIAL (SLM)
master m1; 145 m1.input(); m1.getpay(); m1.getexp(); m1.gettotal(); m1.person::display(); m1.account::display(); m1.admin::display(); m1.display(); return 0; Output: Enter the name of the person : Chetali Enter the code of the person : 1224 Enter the pay : 20000 Enter the experience : 2 Enter the company name : Hitech Name of the person : Chetali Code of the person : 1224 Pay : 20000 CU IDOL SELF LEARNING MATERIAL (SLM)
Experience : 2 Company name : Hitech 6.5 VIRTUAL BASE CLASS We have just discussed a situation which would require the use of both multiple and multi level inheritance. Consider a situation, where all the three kinds of inheritance, namely multi-level, multiple and hierarchical are involved. Let us say the ‘child’ has two direct base classes ‘parent1’ and ‘parent2’ which themselves has a common base class ‘grandparent’. The child inherits the traits of ‘grandparent’ via two separate paths. It can also be inherit directly as shown by the broken line. The grandparent is sometimes referred to as ‘INDIRECT BASE CLASS’. Now, the Inheritance by the child might cause some problems. All the public and protected members of ‘grandparent’ are inherited into ‘child’ twice, first via ‘parent1’ and again via ‘parent2’. So, there occurs a duplicacy which should be avoided. The duplication of the inherited members can be avoided by making common base class as the virtual base class: for e.g. 146 CU IDOL SELF LEARNING MATERIAL (SLM)
Program to show the virtual base class 147 #include<iostream.h> #include<conio.h> class ClassA { public: int a; }; class ClassB : virtual public ClassA { CU IDOL SELF LEARNING MATERIAL (SLM)
public: int b; }; class ClassC : virtual public ClassA { public: int c; }; class ClassD : public ClassB, public ClassC { public: int d; }; void main() { ClassD obj; obj.a = 10; //Statement 1 obj.a = 100; //Statement 2 obj.b = 20; obj.c = 30; 148 CU IDOL SELF LEARNING MATERIAL (SLM)
obj.d = 40; cout<< \"\\n A : \"<< obj.a; cout<< \"\\n B : \"<< obj.b; cout<< \"\\n C : \"<< obj.c; cout<< \"\\n D : \"<< obj.d; } Output : A : 100 B : 20 C : 30 D : 40 According to the above example, ClassD have only one copy of ClassA and statement 4 will overwrite the value of a, given in statement 3. 6.6 OVERRIDING MEMBER FUNCTION If there are two functions with the same name in the base class and derived class and even the address of derived class is assigned to the pointer of base class; it executes the function of base class. But by declaring the base class function as virtual, pointer to base class executes the function of derived class. And in this way base class pointer behaves differently at different situation and applies the concept of polymorphism. This is also called run time or dynamic polymorphism because when a function made virtual, C++ determines which function to use at run time based on the type of object pointed to by the base pointer, rather than the type of the pointer. 149 CU IDOL SELF LEARNING MATERIAL (SLM)
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265