0% found this document useful (0 votes)
10 views

Inheritance, polymorphism and pointer

Unit 7 covers key concepts in object-oriented programming, including inheritance, polymorphism, and pointers. It explains various types of inheritance (single, multi-level, hierarchical, and hybrid), the role of virtual functions in achieving runtime polymorphism, and the use of pointers to manage memory and objects. The unit also includes examples and exercises to reinforce understanding of these concepts.

Uploaded by

Heureuse
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)
10 views

Inheritance, polymorphism and pointer

Unit 7 covers key concepts in object-oriented programming, including inheritance, polymorphism, and pointers. It explains various types of inheritance (single, multi-level, hierarchical, and hybrid), the role of virtual functions in achieving runtime polymorphism, and the use of pointers to manage memory and objects. The unit also includes examples and exercises to reinforce understanding of these concepts.

Uploaded by

Heureuse
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/ 35
Unit 7: Inheritance, Polymorphism and Pointer Notes Structure 7.1 Introduction 72. Inheritance 73 Denived class 734 Access Control 7.4 Type of Inheritance 7.44 Single Inheritance 7.42 Multi Level Inheritance 7.43 Hierarchical Inheritance 7.4.4 Hybnd inhentance 7.5 Polymorphism 76 Pointer 7.6.4 The Pointer Operators 77 Pointer to object 78 This Pointer 79 Pointer to derived class 7.10 Virtual Functions 7.11 Pure virtual funetion With Pointers 7.12 Virtual Base Class 7.13 Abstract Classes 7.14. Constructor in denved class 745 Summary 7.48 Check Your Progress 7.17 Questions and Exercises 718 Key Toms 7.19 Further Readings Objectives After studying this unt, you should be able to ‘© Understand Inheritance @ Discuss the concept of virtual function. © Explain the concept of templates 7.1 Introduction A pointer is variable that holds a memory address. This memory address is the location of other objects (typically another variable) in memory. For example, if one 144 Notes ‘Object Oriented Programming wit C+ variable contains the address of another variable, the frst variable is said to point to the second In this lesson we will going to learn about inheritance, pointer, template, 7.2 Inheritance Inheritance is 2 key feature of object-oriented programming in which a new class (derived class) is created from an existing class(base class). The derived class inherits all feature from a base class and it can have additional features of ts own 7.3 Derived class A class can be derived from more than one classes, which implies it can acquire data and capacities from numerous base classes. To characterize a derived class, we ullize a class determination rundown to indicate the base class(es). A class inference list ‘names one or more base classes and has the structure: class derived.class: access-specifier base-class Where access-specifier is one of open, secured, or private, and base-class is the name of a formerly characterized class. In the event that the entrance specifier is not utilized, then itis private neturelly Consider a base class Shape and its derived class Rectangle as take after include using namespace std Base class class Shape { open: void setWidthiint w) { width = w; } void setHeight(int h) { height = hy } secured int width; int height, % Derived class class Rectangle: open Shape { open Inectance, Polymorphism and Pointer int getArea() retum (width * height) y: ii int main(void) ( Rectangle Rect Rect setwidth(5) Rect setHeignt(7) (Print the zone of the article cout << "Aggregate zone: " << Rect getArea() << endl retum 6: ) At the point when the above code is aggregated and executed, it delivers the accompanying result Output : 35 7.3.1 Access Control We should recollect that a determined class can access all the non-private members of its base class. Consequently, base-class members that ought not be accessible to the part functions of inferred classes ought to be proclaimed private in the base class. We can compress the diverse access sorts as indicated by who can access them in the accompanying way. Table 1.1 Different Types of Access Acces Public | Protected | Private Same class yes__| ves es Derivedclasses [yes | Yes no Outside classes | yes | No no A derived class inherits all base class methods with the following exceptions: © Constructors, destructor and copy constructors of the base class © Overloaded operators of the base class. © The friend functions of the base class 7.4 Type of Inheritance While using different type of inheritance, following rules are applied © Public Inheritance When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived Class. A base class's private members are naver accessible directly from a derived 145 Notes 146 Notes ‘Object Oriented Programming wit C+ class, but can be accessed thraugh calls to the public and protected members of the base class. © Protected Inheritance: When deriving from a protected base class, public and protected members of the base class become protected members of the denved class © Private Inheritance: When deriving from a private base class, public and protected members of the base class become private members of the derivad class, 7.44 Single Inheritance In single inheritance, there is only one base class and only one derived class. A Super Class B Sub Class Example: Single Level Inheritance 7.4.2 Multi Level Inheritance In this, there will be a chain of inheritance with @ class derived from only one parent and will have only one child class. Inectance, Polymorphism and Pointer Example: Multi Level Inheritance 7.4.3 Hierarchical Inheritance Hierarchical Inheritance is a method of inheritance where one or more derived classes are derived from common base class 147 Notes 148 (Object Oriented Programming wit C++ Notes Syntax class base_classname { properties methods; ) class derived_classt visibility mode base_classname { properties, methods, by class derived _class2:visibility mode base classname { properties methods, ) class derived_classN-vsibilty_mode base_classname { properties methods, % Inectance, Polymorphism and Pointer 7.4.4 Hybrid Inheritance In this one or more types of inheritance are combined together and used. In this diagram below combination of Hiererchical and Multilevel Inheritance is shown A o Qa 7.5 Polymorphism Polymorphism is an important OOP concept Polymorphism means the ability to take more than one form. For example, an operation may exhibit different behavior in different instances. The behavior depends upon the types of data used in the operation For example, consider the operation of addition. For two numbers, the operation will generate @ sum. If the operands are strings, then the operation will produce a third string by contention. The diagram given below. illustrates that a single function name can be used to handle different number and types of arguments. This is something similar to a particular word having several different meanings depending on the context Polymorphism plays an important role in following objects having different intemal structures to share the same external interface. This means that a general class of operations may be accessed in the same manner even though specific actions associated with each operation may differ Polymorphism can be implemented using operator and function overioading, where the same operator and function works differently on different arguments producing different results. These polymorphisms are brought into effect at compile time itself, hence is known as early binding, static binding, static linking or compila time polymorphism, However, ambiguity creeps in when the base class and the derived class both have a function with same name. For instance, let us consider the following code snippet. 149 Notes 150 Notes ‘Object Oriented Programming wit C+ @ display) decived class Since, both the functions aa cisplay() and bb.display() are same but at in different classes, there is no overloading, and hence early binding does not apply. The appropriate function is chosen at the run time run time polymorphism, C++ supports run-time polymorphism by @ mechanism called virtual function. it exhibits late binding or dynamic linking. As slated earlier, polymorphism refers to the property by which objects belonging to different classes are able to respond to the same message, but in different forms. Therefore, an essential feature of polymorphism is the ability to refer to objects without any regard to their classes. It implies that a single pointer variable may refer to object of different classes. However, @ base pointer, even if is made to contain the address of the derived class, ahvays executes the function in the base class. The compiler ignores the content of the pointer and chooses the member function that matches the type of the pointer. Thus, the polymorphism stated above cannot be implemented by this mechanism. C++ implements the runtime abject polymorphism using a function type known as Virtual function. When a function with the same name is used both in the base class and the derved class, the function in the base class is declared virtual by attaching the keyword virtual in the base class preceding its normal declaration. Then C++ datermines which function to use at run time based on the type of abject pointed to by ‘the base pointer rather than the type of the pointer. Thus, by making the base pointer to point to different objects, one can execute different definitions of the virluel function as given in the program below. coue<<”\n print ba @ show () us Inortanes, Polymorphism and Pointsr courx<"\n display derived”? out<<""\n show derived"; basepts -> show/ <<\n\nbaee! és basepts -> displ => show0)t ‘ ? The output of this program would be Here, we see that the same abject pointer points to two different objects of different classes and yet solocts the right function to execute. This is implementation of function polymorphism. Remember, however, that runtime polymorphism is achieved only when a virlual function is accessed through a pointer to the base class. It's also intoresting to note that since, all the C++ classes are derived from the Object class, a pointer to the Object class can point to any objact of any class in C++ 7.6 Pointer Ifa variable is going to hold a pointer, it must be declared as such. A pointer declaration consists of a base type, an *, and the variable name. The general form for declaring @ pointer variable is type * name: 151 Notes 182 Notes ‘Object Oriented Programming wit C+ where type is the base of the pointer and may be any valid type. The name of the pointer variable is specified by name. The base type of the pointer defines what type of variables the pointer can point to. Technically, any type of pointer can point anywhere in memory. However, all pointer arithmetic \s done relative to its base type, so it is important to declare the pointer correctly 7.8. The Pointer Operators We will tke a closer look at the Pointer operators here, beginning with a review of their basic operation. There are two special pointer operators: * and & The & is @ unary ‘operator that retumns the memory address of its operand. (Remember, a unary operator only requires one operand ) For oxamplo, m= &count place into m the memory address of the variable count. This address is the computer's Internal location of the variable. It has nothing to do with the value of count. You can think of & as returning "the address of * Therefore, the preceding assignment statemant means “m receives the address of count’. To understand the above assignment better, assume that the variable count uses memory location 2000 to store its value. Also assume that count has a value of 100. Then, after the preceding assignment, m will have the value 2000, ‘The second pointer operator. *, is the complement of & It is @ unary operator that returns the value located at the address that follows. For example, if m contains the memory address of the variable count, q=tm; places the value of count into g. Thus, q will have the value 100 because 100 is stored at location 2000, which is the memory address that was stored in m. You can think of “ac ” at address.” in this case, the preceding statement means "g receives the value at address m’" Both & and * have a higher precedence than all other arithmetic operators except the unary minus, with which they are equal You must make sure that your pointer variables always point to the correct type of data, For example, when you declare a pointer to be of type int, the compiler assumes ‘nat any address that it holds point to an integer variable — whether it actually does or not. Because C allows you to assign any address to @ pointer variable, the following code fragment compiles with no error messages (or only warnings, depending upon ‘your compiler), but does not produce the desired result 2 inc: o.h> double x = 100.1, v pointer) to point = atetenent causes 5 Inortanes, Polymorphism and Pointsr ‘This will not assign the value of x to y. Because p is declared as an integer pointer, only or 4 bytes of information will be transferred to y, not the 7 bytes that normally make up a double. In C+4, itis illegal to convert one type of pointer into another without the use of an explicit type cast. For this reason, the preceding program will not even compile if you try to compile it as a C++ (rather than as a C) program. However, the type of error ascribed can still occur in G+* in a more roundabout manner. 7.7 Pointer to object A variable that holds an address value is known as a pointer variable or pointer. Pointer can point to object, simple data type and arrays. Sometime we did not know about the number of objects we need at the time when we start writing the program. In that case, we write new to create objects during program execution, Consider an example of pointer to object: #include #include using namespace std, class student t private introlino; string name public: student()rollno(0),name(™) a student(intr, string n):rolino(s),name (n) a void get() { coute<"enter roll no” cine>rollno; couts<‘enter name", cino>name } void print() C 183 Notes 184 Notes ‘Object Oriented Programming wit C+ cout<<"roll no is "< de len{strl) : << len << and: When the above code is compiled and executed, it produces result something as follows: The String Class in C++: ‘The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality. We will study this class in C++ Standard Library but for now lat us check following example Inortanes, Polymorphism and Pointsr At this point, you mey not understand this example because so far we have not discussed Classes and Objects. So can have a look and proceed until you have understanding on Object Oriented Concepts ude using nanesp: xc sted << al lenghth of etz3 a size): When the above code is compiled and executed, it produces result something as follows: Helle ete + at sistiozia str3.sizeQ) + 10 String Manipulation in C++ The Standard String Class (strings) We will usually refer to these things as strings, and the other type as c-strings or ntcas. One fact that you want to Keep in mind is that they are indeed of different type, so you 187 Notes 158 Notes (Object Oriented Programming wit O-+ cannot expect the compiler to understand you if yau start to mix them. There is a set of functions available to the programmer for the manipulation of standard stings. Some compilers will have them and some will not In order to access them in the GNU compiler, you will need to include the system filo string. Thus, when using more specialized string class functions, put the preprocessor command. de at the top of your program with other system includes. | will leave it up to you to discover the different functions allowing you to manipulate standard stings by looking ‘them up in the text or on-line. They are numerous and varied. But remember, the GNU compiler may not have them available and you will have to work around them. .c character-by-character using get() Each of these methods has an advantage, but it depends on the requirements of the problem. Ifyou need to process each cheracter, then read cher-by-char. If you need to process each word, then use cin=> ‘The put () function is actually fairly useless, is equivalent to ‘av; End of discussion! The puck: stream (0 function will allow you fo put a charactor back into the input cin.putbackt(chay var) s The peek () function will allow you to know what the next character in the input stream is without extracting from that stream. All these functions will allow 2 certain degree of manipulation of the input stream and its contents for single characters, 7.8 This Pointer When @ member function is called, itis automatically passed an implicit argument that is a pointer to the invoking object (that is, the object on which the function is called). This pointer is called this. To understand this, first consider a program that creates a class called pwr that computes the result of a number raised to some power: 161 Notes 162 Notes (Object Oriented Programmimg with C+ pwr (double base, i ble base, al te: sget pwr() <<" An": Within a member function, the members of a class can be accessed directly, without any object or class qualification. Thus, inside pwr(), the statement ase; means that the copy of b associated with the invoking object will be assigned the value contained in base. However, the same statement can also be written lke this. this>t ase, The this pointer points to the object that invoked pwn). Thus, this-»b rafers to that object's copy of b. For example, if pwr) had been invoked by x (as in x (4.0,2)), then this in the preceding statement would have been pointing to x, Writing the statement without using this ts really just shorthand Here is the entire pwr() function written using the this pointer Inortanes, Polymorphism and Pointsr Actually, no C++ programmer would write pwr() as just shown because nothing is gained, and the standard form is easier. However, the this pointer is very important when operators are overloaded and whenever a member function must utlize a pointer to the object that invoked it Remember that the this pointer is automatically passed to all member functions. ‘Therefore, get_pwri) could also be rewritten as shown here ouble pee () [xeturn In this case, if get_pwr() is invoked lke this prs (): Then this will pint to object two final points about this. Fits, fiend functions are not members of a class and, therefore, are not passed this pointer. Second, state member funetions do not have a this pointer 7.9 Pointer to derived class #include ulilizing namespace st class BaseCiass { intx, public Void setx(int) { =I ) int getx() { retum x; ) ® class DerivedClass | public BaseClass { inty, public. 163 Notes 164 Notes ‘Object Oriented Programming wit C+ void sety(int I) { int gety0{ return y, } k int main) ci BaseClass "p pointer to BaseClass type BasoClass baseObject,/ object of BaseClass DerivedClass derivedObject,/ object of DerivedClass p= baseObject; use p to gat to BaseClass object psatx(10) Jaccess BaseClass object cout << "Base item x:" << pogetx() << "' p= 8derivedObject, /point to DerivedClass object po>setx(99) faccess DerivedClass object derivedObject sety(38) ‘can't utlize p to set y, so do it specifically cout << "Determined item x. " << p->getx() <<, cout << "Determined item y- " << derivedObject gety() << return 0 ) 7.10 Virtual Functions Virtual means existing in effect but not in reality. A viual function then is one that does not really exist but nevertheless appears real to some parts of a program. Consider an example, which explains the need of virlual function: Suppose you have a number of objects of different classes but you want to put them all on a list and perform a particular operation on them by using the same function call. For example, Suppose @ graphics program include several different shapes: a tangle, a ball, a square, and so on. Each of these class has a member function draw() that causes the object to be drawn on the screen. Now suppose you plan to make a picture by grouping a number of these elements together, and you want to draw the picture in a convenient way. One approach is to create an array that holds pointers to all the different objects in the picture. The array might be defined like this. shape" ptrass [100]; !/ array of 100 pointers to shapes Inortanes, Polymorphism and Pointsr If you insert pointers to all the shapes into this array, you can then draw an entire Picture using a simple loop: for(int jeN, j++) ptrass{] > draw) In virtual function, completely different functions are executed by the same function call. If the pointer in ptrass points to a ball, the function that draws @ ball is called: fit points to a triangle, the triangle-drewing function is drawn. This is an important example of polymorphism, or giving different meanings to the same thing. However, for this polymorphic approach to work, several conditions must be met First, all the different classes of shapes, such as balls and trangles, must be derived from a single base class. Second, the draw ( ) function must be declated to be virtual in the base class. Consider the program given below to clearly understand the virtual function: ude 3 enor) <<"\n show base show() show 165 Notes 166 Notes ‘Object Oriented Programming wit C+ Derived 2; // Declarations Base *bper? pointe te Derived \n"s Note that when bptr is made to point tothe object D, the statement bptr ->display(), calls only the function associated with the Base (i.e. Base = display( } ) whereas the statement bptr ->show() Calls the Derived version of show ( ). This 's because the function display ( ) has not been made virtual in the Base class. One important point to remember is that, we must access virtual functions through ‘the use of @ pointer declared as a pointer to the base class. Why cant we use the object name (with the dot operator) the same way as any other member function to call ‘the virtual function? We can, but remember, runtime polymorphism is achieved only when a virtual function is accessed through a pointer to the base class, 7.11 Pure virtual function With Pointers Let's make a single change in our program. Weill place the keyword virtual in front of ‘the declarator for the show () function in the base class. Here's the listing for the resulting program, VIRT Inortanes, Polymorphism and Pointsr W vires opp <<"\n Base // devived class1 <<"\n Dervt / derived cla 167 Notes 168 Notes ‘Object Oriented Programming wit C+ The output of this program is, Now, as you can see. th member functions of the derived classes, not the base class, are executed. We change the contents of ptr from the address of Dervt to that of Derv2, and the particular instance of show ( ) that is executed also changes. So the same function call, ptr >show ( ) executes different functions, depending on the contents of ptr. The rule is that the compiler selects the function based on the contents of the pointer pir, not on the type of ‘the pointer, as in NOT VIRTUAL. 7.12 Virtual Base Class ‘Assume you have two derived classes B and C that have a common base class A, and ‘you additionally have another class D which is inheritad from B and C. You can declare ‘the base class A as virtual to guarantee that B and C share the same subobject of A In the accompanying illustration, an object of class D has two particular subobjects of class L, one through class B1 and another through class B2. You can use the keyword virtual before the base class specifiers in the base lists of classes B1 and 82 to show that one and only subobject of type L, shared by class 61 and class B2, exists. For example: vir class L (/"..*/}; (V indirect base class. class 81 virtual public L{/* ..*/}: class B2: virtual public L{/" ..*!}; class D public B1, public B2 (/*... */); {f valid L Using the keyword virtual in this example ensures that an object of class D inherits only one subobject of class L 7.13 Abstract Classes Abstract Class is a class which contains alleast one Pure Virtual function in il, and is use to give an Interface to its sub classes. Classes acauiring an Abstract Class must provide definition to the pure viral function, else they will also become abstract class Inertance, Polymorphism and Pointer Characteristics of Abstract Class © Abstract class can't be instantiated Abstract class can have normal functon and variables along wih a pure vitual junction An interface describes the behavior or capabilities of a G++ class without committing to @ particular implementation of that class ‘The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation details separate from associated data A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual functon is specified by placing "= 0" in tts declaration as follows: es Box ach J) Beis! ‘The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class fram which other classes can inherit, Abstract classes cannot be used fo instantiate objects and serves only as an interface Attempting to instantiate an object of an abstract class causes a compilation error. ‘Thus, if @ subclass of an ABC needs to be instantiated, it has to imploment each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override’ a pure virluel function in a derived class, then attempting to instantiate objects of that class, is a compilation error. Classes that can be used to instantiate objects are celled conerete classes. Abstract Class Example: Consider the following example where parent class provides an interface to the base class to implement a function called getArea() ueing nanesp: 169 Notes 170 Notes (Object Oriented Programmimg with C+ void setmideh (int w) inc widchr int getarea() ei Inortanes, Polymorphism and Pointsr © * << tri, 2a) << en When the above code is compiled and executed, it produces the following result: Total Rectangle area: 35 jotel Triangle area: 17 You can see how an abstract class defined an interface in terms of gotArea() and two other classes implemented same function but with different algorithm to calculate the area specific to the shape Designing Strategy: ‘An object-oriented system might use an abstract base class to provide a common and standardized interface appropriate for all the external applications. Then, through inheritance from that abstract base class, derived classes are formed that all operate similarly. The capabiities (ie, the public functions) offered by the extemal applications are provided as pure virtual functions in the abstract base class. The implementations of these pure virtual functions are provided in the derived classes that correspond to the ‘specifi types of the application This architecture also allows new applications to be added to a system easily, even after the system has been defined 7.14 Constructor in derived class Acconstructor assumes a vital part in initializing an object. An essential note, while using constructors during inheritance, is that, as long as a base class constructor does not take any arguments, the derived class need not nave a constructor function. However. if a base class contains a constructor with one or more arguments, then itis necessary for the derived class to have a constructor and pass the arguments to the base class constructor. Keep in mind, while applying inheritance, we usually create objects using derived class. Thus denved class pass arguments fo the base class constructor. , the base constructor is executed first and then the constructor in the derived class is executed, Illustration: Program to show now constructor aré invoked in derived class #include 171 Notes 172 Notes class alpha ( private intx: public: alpha(int i) { xi, cout << "\n alpha initialized \n" y void show_x0 { cout << "Inx = "ex; } ) class beta ( private: float y, public: beta(fioat j) { yeh cout <<"tn beta initialized \n" y void show_y() { cout << "ny = "cy; , x class gamma public beta, public alpha ( private inta.m, public: gammatint a, float b, int c, int d): alpha(a), beta(b) (Object Oriented Programmimg with C+ Inhoctancs, Polymorphism and Point 173 t mSE Notes n=d; cout << "in gamma initialized \n" 3 Void show_mn() t void main() £ gamma g(5, 7.65, 30, 100): cout << g.show_x0; gshow_y() g.show_mn() } Output beta initialized alpha intialzed gamma initialized xe8 y=705 m=30 n= 100 7.15Summary In this chapter we studied about pointer, inheritance, types of inheritance, use of constructor in derived class and about tompiate Pointers provide an essential tool for increasing the power of C++. Whereas inheritance allow us to get the features of base class in derived class by various means 174 Notes ‘Object Oriented Programming wit C+ 7.16 Check Your Progress Multiple Choice Questions 1. To what does the function pointer point to? a) variable b). constants ©) function d) absolute variables 2. What we will not do with function pointers? a) allocation of memory b) de-allocation of memory ©) both a&b ) none of the mentioned 3. What is the defautt calling convention for a compiler in c++? a) _sdecl b) _stdcall ©) __pascal @) _testcal 4. What is the output of this program? #include using namespace std Int add(int frst, int second) C return frst + second + 15) int operation(int first, int second, int *functocall}int, int)) t retum (“functocall)first, second); } int main() { inte int *plus}(int, int) = add; a= operation(16, 10, plus) cout < Inortanes, Polymorphism and Pointsr 175 using namespace std, void func(int x) Notes t cout using namespace sta int n{char, int); int*p) (cher, int intmaing ( Cone, 9; (10, 9) retum 0 ) int n(char int) ( cout << <<: return 0, } a) doo b) dec ©) do d)_ compile time error 7. What is the output of this program? #include using namespace std, Int func (inta, int b) { cout <

You might also like