KEMBAR78
C | PDF
0% found this document useful (0 votes)
12 views28 pages

C

VTU text book

Uploaded by

skydrake34
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
12 views28 pages

C

VTU text book

Uploaded by

skydrake34
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 28
Inheritance: | Extending Classes YV¥VYV¥Y¥Y¥YYY¥Y¥YYYYY ¥ Key Concepts Reusability Inheritance ‘Single inheritance Multiple inhe Multilevel ° tance Hybrid inh ance Hierarchical inheritance: Defining a derived class Tnheritiing private members Virtual base class Direct base class Indirect base class Abstract class Defining derived class constructors Nesting of classes 8.1 Introduction Reusability is yet another important feature of OOP. It is always nice if we could reuse something that already exists rather than trying to create the same all over again. It would not only save time and money but also reduce frustration and inerease reliability. For instance, the reuse of a class that has already been tested, debugged and used many times can save us the effort of developing and testing the same again. Fortunately, C++ strongly supports the concept of reusability. The C++ elasses ean be reused in several ways. Once a class has been written and tested, it can be adapted by other programmers to suit their requirements, This is basically done by creating new classes, reusing the properties of the existing ones. The mechanism of deriving a new class from an old one is called inheritance (or derivation). The old class is referred to as the base class and the new one is called the derived class or subclass. Copyrighted material 2020—_—_——————_ Object-Oriented Programming with C++ The derived class inherits some or all of the traits from the base class. A class can also inherit properties from more than one class or from more than one level. A derived class with only one base class, is called single inheritance and one with several base classes is called multiple inheritance. On the other hand, the traits of one class may be inherited by more than one class, This process is known as hierarchical inheritance. The mechanism of deriving a class from another ‘derived class’ is known as multilevel inheritance. Figure 8.1 shows various forms of inheritance that could be used for writing extensible programs. The direction of arrow indicates the direction of inheritance. (Some authors show the arrow in opposite direction meaning “inherited from".} \] | cy] B Le D (0) Api terance fase teens r ea 1 + B 8 {e a 3 tn maven pews Saco Fig. 8:1. <> Forms of irihevitance l Defining Derived Classes A derived class can be defined by specifying its relationship with the base class in addition to its own details. 'The general form of defining a derived class is: Copyrighted material Inheritance; Extending Classes. ———@ 203. class derived-class-name : vistbility-mode base-class-name Al /| menbers of derived class The colon indicates that the derived-class-name is derived from the base-class-name. The visibility-mode is optional and, if present, may be either private or public. The default visibility-mode is private. Visibility mode specifies whether the features of the base class are privately derived or publicly derived. Exampk class ABC: private KYZ // private derivation { members of ABC class ABC: public XYZ // public derivation members of ABC h class ABC: XYZ // private derivotion by default ‘ members of ABC h When a base class is privately inherited by a derived class, ‘public members’ of the base class become ‘private members’ of the derived class and therefore the public members of the ‘base class can only be accessed by the member functions of the derived class. They are inaccessible to the objects of the derived class. Remember, a public member of a class can be accessed by its own objects using the dot operator. ‘The result is that no-member of the base class is accessible to the objects of the derived class. On the other hand, when the base class is publicly inherited, ‘public members’ of the base class become ‘public members’ of the derived class and therefore they are accessible to the objects of the derived class. In both the cases, the private members are not inherited and therefore, the private members of a base class will never become the members of its derived class. In inheritance, some of the base class data elements and member funetions are ‘inherited’ into the derived class. We can add our own data and member functions and thus extend the Copyrighted material 204.0 —_ Object-Oriented Programming with C++ functionality of the base class. Inheritance, when used to modify and extend the capabilities of the existing classes, becomes a very powerful tool for incremental program development. I Single Inheritance Let us consider a simple example to illustrate inheritance, Program 8.1 shows a base class B and a derived class D. The class B contains one private data member, one public data member, and three public member functions. The class D contains one private data member and two public member functions. pial te bes finclude using namespace std; class 8 { int-ay // private; not inheritabie public int by f{ publics ready for inheritance void get_db(}; int get a(void); void show_a(void); i class D; public B // public derivation { int c; public, woid mul (void); void display(void); ie Mfr void B i: get_ab(void) { a= 5 b= 10; } int 6 :: get_a() { return a3 I void B13 show_a() { (Contd) Copyrighted material Inheritance: Extending Classes ——————® 205 cout << "a=" << a << "\n"; } void D sz mul() { c= b* get ats ) void 0 :: display() { cout << "a= * << get_a() <¢ "\n"; cout <¢ "hs * ce hee “\nty cout << "c= * << ¢ << *\n\n d.get_ab(); d.mul(); d.show_a(); d.display()s d.b = 20; d.mul()5 d.display(); return O; Given below is the output of Program 8.1: a-5 a=5 b= 10 c= 50 aes b= 20 c= 100 The class D is a public derivation of the base class B. Therefore, D inherits all the public members of B and retains their visibility, Thus a public member of the base class B is also a public member of the derived class D. The private members of B cannot be inherited Copyrighted material 206e—___—_——_ Object-Oriented Programming with C++ by D. The class D, in effect, will have more members than what it contains at the time of declaration as shown in Fig. 8.2. mull) dispiay() Fig.82 43 Adding more members to a class (by public derivation) ‘The program illustrates that the abjects of class D have access to all the public members of B. Let us have a look at the functions show_a() and mul(); void show_a() cout << "a= "<> a >> b y int B :: get_a() { return a; } void B :: show a() { cout << "gs * ce a xe *\nty void D :: mul() (ees get_ab()i 5 b * get_a()s // ‘a’ cannot be used directly?!) Devas ¥ enh ed ie otk sie ee: void D :: display() f = show_a() J/ outputs value of ‘a! cout << "b= "ce b Access mechanism in classes Ie. 5 Multilevel Inheritance It is not uncommon that a elass is derived from another derived class as shown in Fig. 8.7. ‘The class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. The class B is known as intermediate base class since it provides a link for the inheritance between A and C. The chain ABC is known as inheritance path. Copyrighted material 214 @———_ ject Oriented Programming with C++ Allusers derived class private | ‘own member functions member and friendly functions funetions and classes protected Fig. 86 2A simple view of access control to the members of a class Base class [A] Grandtather Intermediate Sarat [oe | rene Derived cass |G | Child Fig.8.7 <> Multilevel inheritance ” A derived class with multilevel inheritance is declared as follows: ahs Jf Bose class public A [....013 // 8 dertved from A public B {..eeeds Jf C derived from & class Af class class This process can be extended to any number of levels. ‘Let us consider a simple example. Assume that the test results of a batch of students are stored in three different classes. Class student stores the roll-number, class test stores the marks obtained in two subjects and class result contains the total marks obtained in the test. The class result can inherit the details of the marks obtained in the test and the roll- number of students through multilevel inheritance. Example: Copyrighted material Inheritance: Extending Classes. ———————— 215 class student 1 protected: int rol]_numbers public: void get_nunber(int); void put_nunber (void) ; void student :: get_number(int a) . { © rell_number * 33 ' void student :: put_number() { cout << "Roll Number: " << roll_number << "\n ' class test : public student // First tevel derivation { protected: float subl; Float sub2s public: void get_marks(float, float); void put_marks (void) ; hi void test :: get_marks(float x, float y) { subl = x; sub2 = yz 1 void test =: put_marks() { cout << “Marks im SUBL = " << sub] << "\n*; cout << "Marks in SUBZ = " << sub? << "\n"; I class result : public test fj Second level derivation { float total; // private by defouit public: void display(vo } The class result, after inheritance from ‘grandfather’ through ‘father’, would contain the following members: Copyrighted material 216 @—$<$@—___—__—— Object-Oriented Programming with C++ private: float total; Af onn member protected: int rol]_numbers // inherited from student via test float subl; if inherited from test float sub2; // inhertted from test publics void get_number(int); // from student vio test void put_number(void) ; jj from student vio test void get_marks(float, float); if from test void put_marks (void); Af from test _void display(void) ; Jf own member The inherited functions put_number() and put_marks() can be used in the definition of display() function: void result i: display(void) ‘total = subl + sub2; put_number() 5 put_marks(); cout << "Total = " << total << "\n"; } Here is a simple main() program: int main() result studentl; /} Student1 created student1.get_number(111); Studentl.get_marks(75.0, 59.5); student.display()s return 0; } This will display the result of student. The complete program is shown in Program 8.3. ce ate aE Las #include Multiple inheritance Copyrighted material Inheritance: Extending Classes. 219 The syntax of 'a derived class with multiple base classes is as follows: class D: visibility B-1, visibility B-2 ... ( where, visibility may be either public or private. The base classes are separated by commas. Example: class P : public M, public N ( public: void display(void); h Classes M and N have been specified as follows: class M { protected: int m; public: void get_m(int): hs void Mz: get_m(int x) { } class N { protected: int public: void get_n(int); mx hs void N :: get_n(int y) { Copyrighted material 220@———- Object-Oriented Programming with C++ n= ye + ‘The derived class P, as declared above, would, in effect, contain all the members of M and N in addition to its own members as shown below: class P { Ee protected: it Uf from t Vi from public: void get_m(int); LW from # void get_n(int); MW from void display(votd): Lown member h ‘The member function display() can be defined as follows: void P :: display(void) { cout << "m= " << m << "\n"; cout << "n= "<< n << "\n"; cout << "mn =" << m*n << "\n"s The main() function which provides the user-interface may be written as follows: main() { Pp; p.get_m(10); peget_n(20); p.display();, } Program 8.4 shows the entire code illustrating how all the three classes are implemented in multiple inheritance mode. Copyrighted material Inheritance: Extending Classes CRs eas Us ae ad #include using namespace std; class M { protected: int m public: void get_m(int); hs class N { protected: int m3 public: void get_n(int); i class P : public M, public N { publict void display (void); hi void M { 1 : get_m(int x) mex void N :: get_n(int y) { : } void P { ney; + display(votd) cout << "m= "<< mc "\n"; cout << "n= * <¢n << "\n cout << “mn =" << mtn << int main() (Contd) Copyrighted material 222 @ ject Oriented Programming with C++ Pp p.get_m(10) ; p.get_n(20) 5 pedisplay() 5 return 0; ROGRAM &.4 ‘The output of Program 8.4 would be: m= 10 n= 20 mn = 200 Ambiguity Resolution in Inheritance Oceasionally, we may face a problem in using the multiple inheritance, when a function with the same name appears in more than one base class. Consider the following two classes, class M public: void display(votd) { cout << "Class M\n"; i class N { public: void display (void) { cout << "Class Nin"; ) VM Which display() function is used by the derived class when we inherit these two classes? We can solve this problem by defining a named instance within the derived class, using.the class resolution operator with the function as shown below: class P : public M, public N Copyrighted material Inheritance: Extending Classes. —————® 223 ( public: void display (void) J/ overrides display() of M and N { } M ss display(); )s ‘We can now use the derived class as follows: int main() { Pps ; p.display(); Ambiguity may also arise in single inheritance applications. For instance, consider the following situation: class A { public: fo display() cout << "An"; } hs class 8 : public A { public: void display() { } cout << "B\n"; hs In this case, the function in the derived class overrides the inherited function and, therefore, a simple call to display() by B type object will invoke function defined in B only. However, we may invoke the function defined in A by using the scope resolution operator to specify the class. Example: int main() { Copyrighted material 2240e————_———_. Object-Oriented Programming with C++ // derived class object // invokes display() in B ff invokes display() in A Jf invokes display() in B return Os ! This will produce the following output: 8 A B [s.7 Hierarchical Inheritance ‘We have discussed so far how inheritance can be used to modify a class when it did not satisfy the requirements of a particular problem on hand. Additional members are added through inheritance to extend the capabilities of a class. Another interesting application of inheritance is to use it as a support to the hierarchical design of a program. Many programming problems can be cast into a hierarchy where certain features of one level are shared by many others below that level. ‘As an example, Fig. 8.9 shows a hierarchical classification of students in a university. Another example could be the classification of accounts in a commercial bank as shown in Fig. 8.10. All the students have certain things in common and, similarly, all the accounts possess certain common features. Medical Mech, Elec. | civil Copyrighted material Inheritance: Extending Classes. 225, Account Savings account Fig. 8:10 3 Classification of hank rccounts In C++, such problems can be easily converted into class hierarchies. The base class will include all the features that are common to the subclasses. A subclass can be constructed by inheriting the properties of the base class, «A subclass can serve as a base class for the lower level classes and so on. 8.8 Hybrid Inheritance There could be situations where we need to apply two or more types of inheritance to design a program. For instance, consider the case of processing the student results discussed in See. 8.5. Assume that we have to give weightage for sparts before finalising the results. The weightage for sports is stored in a separate class called sports. The new inheritance relationship between the Various classes would be as 8.1L Multilevel, mult inheritrce | shown in Fig. 8.11. peraees es Copyrighted material 226 @—_—- Object-Oriented Programming with C++ ‘The sports class might look like: class sports { protected: float scores public: void get_score(flo: void put_score(voi 1 The result will have both the multilevel and multiple inheritances and its declaration would be as follows: Class result ; public test, public sports { hi Where test itself is a derived class from student. That is "class test + public student h ~ Program 8.5 illustrates the implementation of both multilevel and multiple inheritance. #include using namespace std; : class student protected: int rol1_numb public: void get_number(int a) . { rol]_number = a; (Contd) CG opy righted material Inheritance: Extending Classes. ————® 227 } void put_number(void) { cout. << "Roll No; " << roll_number << "\n" jass test : public student protected: float partl, part2; public: : void get_marks(float x, float y) : { part] = x; part2 = yz 1 void put_marks (void) { cout << "Marks obtained: " <<."\n" << "Partl = "ce part! << "\n" << “Part? = * << part? << "\nl; Ms class sports { protected: float score; public: void get_score(float s) { score = Si ! void put_score(void) cout << "Sports wt: " << score << "\n\n' i class result ¢ public test, public sports fea { float total; public: void display (void) ; Copyrighted material 228 @—_£_——_————— Object-Oriented Programming with C++ hk void result :: display(void) total = partl + part2 + score; put_number(); put_marks(); put_score(); cout << "Total Score: " << total << "\n"j } int main() result student_1; student_1,get_number(1234); student 1.get marks (27.5, 33.0); Student_l.get_score(6.0); student_l.display(); return 0; ream Here is the output of Program 8.5: Rol] No: 1234 Marks obtained: Partl = 27.5 Part2 © 33 Sports wt: 6 Total Score: 66.5 [s2 Virtual Base Classes We have just discussed a situation which would require the use of both the multiple and multilevel inheritance. Consider a situation where all the three kinds of inheritance, namely, multilevel, multiple and hierarchical inheritance, are involved, This is illustrated in Fig. 8.12. The ‘child’ has two direct base classes ‘parent!’ and ‘parent2' which themselves have a common base class ‘grandparent’. The ‘child’ inherits the traits of ‘grandparent’ via two separate paths. It can also inherit directly as shown by the broken line. The ‘grandparent’ is sometimes referred to as indirect base class. Copyrighted material

You might also like