1 / 79

C++ - Inheritance & Polymorphism

C++ - Inheritance & Polymorphism. Dr.D.Jeya Mala Associate Professor Dept.of Computer Applications Thiagarajar College of Engineering Madurai -15. Tamil Nadu, India.

karik
Download Presentation

C++ - Inheritance & Polymorphism

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ - Inheritance & Polymorphism Dr.D.JeyaMala Associate Professor Dept.of Computer Applications Thiagarajar College of Engineering Madurai -15. Tamil Nadu, India. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  2. Conventional Programming can waste a lot of time while trying reusability to do any modifications or adding new extensions. cut/copy/paste a part of the conventional program, customize it in order to reuse it Due to this patch, it will be harder to locate the errors This reproduction will cause a lot number of cascading side effects in the extended / added code. Conventional approach in Reusability This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  3. Advantage of OO in Reusability • Instead of cut/copy/paste, apply inheritance • This helps you to simply reuse the existing code without any modifications in it. • Any new additions/new implementations can be easily done in the extended version which we call as derived. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  4. Advantages of Inheritance • Code Reusability • Extensibility • Automatic bug fixing in the derived class when a bug is fixed in the base class • Improved readability • Improved supportability This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  5. When to go for inheritance? • Common specifications in many of the classes • Need for variations of a some class in a minimum number of ways (member data and member functions) • Future needs for reusability This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  6. What is Inheritance? • ‘is a’ kind of relationship between classes • One class acquires the properties of another class is called inheritance • Generalization – Specialization kind of relationship • Generalization – Super class/base class/parent class • Specialization – subclass/Derived class /child class • Augmentation – Extended functionality • Eg. • UG Student is a Student • Here Student – base class; UG Student – derived class This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  7. Advantages of inheritance • When a class inherits from another class, there are three benefits: (1) You can reuse the methods and data of the existing class (2) You can extend the existing class by adding new data and new methods (3) You can modify the existing class by overloading its methods with your own implementations This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  8. Rules for building a class hierarchy • Derived classes are special cases of base classes • A derived class can also serve as a base class for new classes. • There is no limit on the depth of inheritance allowed in C++ (as far as it is within the limits of your compiler) • It is possible for a class to be a base class for more than one derived class This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  9. Why Inheritance ? Inheritance is a mechanism for • building class types from existing class types • defining new class types to be a • specialization • augmentation of existing types This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  10. Syntax of Inheritance • Syntax: classDerivedClassName : access-levelBaseClassName where • access-level specifies the type of derivation • private by default, or • public • Any class can serve as a base class • Thus a derived class can also be a base class This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  11. Inheritance – Terminology and Notation in C++ • Base class (or parent) – inherited from • Derived class (or child) – inherits from the base class • Notation: class Student // base class { . . . }; class UGstudent : public student { // derived class . . . }; This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  12. When a derived-class object is created & destroyed • Space is allocated (on the stack or the heap) for the full object (that is, enough space to store the data members inherited from the base class plus the data members defined in the derived class itself) • The base class's constructor is called to initialize the data members inherited from the base class • The derived class's constructor is then called to initialize the data members added in the derived class This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  13. Contd.. • The derived-class object is then usable • When the object is destroyed (goes out of scope or is deleted) the derived class's destructor is called on the object first • Then the base class's destructor is called on the object • Finally the allocated space for the full object is reclaimed This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  14. What Does a Child Have? An object of the derived class has: • all members defined in child class • all members declared in parent class An object of the derived class can use: • all public members defined in child class • all public members defined in parent class This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  15. What is inherited in derived class? This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  16. Class Access Specifiers • public – object of derived class can be treated as object of base class (not vice-versa) • protected – more restrictive than public, but allows derived classes to know details of parents • private – prevents objects of derived class from being treated as objects of base class. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  17. How inherited base class members appear in derived class Base class members private: x protected: y public: z private base class x is inaccessible private: y private: z private: x protected: y public: z protected base class x is inaccessible protected: y protected: z private: x protected: y public: z public base class x is inaccessible protected: y public: z Inheritance vs. Access This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  18. class Grade class Quizgrade: public Grade private members: intnumQuestions; float pointsEach; intnumMissed; public members: Quizgrade(int,int); private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); private members: intnumQuestions: float pointsEach; intnumMissed; public members: Quizgrade(int, int); void setScore(float); float getScore(); char getLetter(); When Quizgradeclass inherits from Grade class using public class access, it looks like this: Inheritance vs. Access This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  19. class Grade class Quizgrade: protected Grade private members: intnumQuestions; float pointsEach; intnumMissed; public members: Quizgrade(int,int); private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); private members: int numQuestions: float pointsEach; int numMissed; public members: Test(int, int); protected members: void setScore(float); float getScore(); float getLetter(); When Quizgradeclass inherits from Grade class using protected class access, it looks like this: Inheritance vs. Access This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  20. class Grade class Quizgrade: protected Grade private members: intnumQuestions; float pointsEach; intnumMissed; public members: Quizgrade(int,int); private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); private members: intnumQuestions: float pointsEach; intnumMissed; void setScore(float); float getScore(); float getLetter(); public members: Quizgrade(int, int); When Quizgradeclass inherits from Grade class using private class access, it looks like this: Inheritance vs. Access This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  21. Constructors and Destructors in Base and Derived Classes • Derived classes can have their own constructors and destructors • When an object of a derived class is created, the base class’s constructor is executed first, followed by the derived class’s constructor • When an object of a derived class is destroyed, its destructor is called first, then that of the base class This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  22. Passing Arguments to Base Class Constructor • Allows selection between multiple base class constructors • Specify arguments to base constructor on derived constructor heading: Cone::Cone(int height) : Shape(side, side) • Can also be done with inline constructors • Must be done if base class has no default constructor This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  23. Constructors and destructors • You cannot override a base class constructor with a derived class constructor (rather, the derived class constructor calls the base class constructor first) • All base class destructors should be declared virtual • Virtual destructors are called in reverse order from the constructors for derived class objects This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  24. Example: Base Class class base { int x; public: void setx(int n) { x = n; } void showx() { cout << x << ‘\n’ } }; This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  25. Example: Derived Class // Inherit as public class derived : public base { int y; public: void sety(int n) { y = n; } void showy() { cout << y << ‘\n’;} }; This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  26. Example: main() int main() { derived ob; ob.setx(10); ob.sety(20); ob.showx(); ob.showy(); } This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  27. Example: Derived Class // Inherit as private class derived : private base { int y; public: void sety(int n) { y = n; } void showy() { cout << y << ‘\n’;} }; This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  28. Example: main() int main() { derived ob; ob.setx(10); // Error! setx() is private. ob.sety(20); // OK! ob.showx(); // Error! showx() is private. ob.showy(); // OK! } This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  29. Example: Derived Class class derived : private base { int y; public: // setx is accessible from within derived void setxy(int n, int m) { setx(n); y = m; } // showx is also accessible void showxy() { showx(); cout<<y<< ‘\n’;} }; This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  30. Protected Members • Sometimes you want to do the following: • keep a member of a base class private • allow a derived class access to it • Use protected members! • If no derived class, protected members is the same as private members. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  31. Protected Members The full general form of a class declaration: class class-name { // private members protected: // protected members public: // public members }; This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  32. 3 Types of Access Specifiers • Type 1: inherit as private This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  33. 3 Types of Access Specifiers • Type 2: inherit as protected This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  34. 3 Types of Access Specifiers • Type 3: inherit as public This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  35. Problem with Redefining • Consider this situation: • Class BaseClass defines functions x() and y(). x() calls y(). • Class DerivedClass inherits from BaseClass and redefines function y(). • An object D of class DerivedClass is created and function x() is called. • When x() is called, which y() is used, the one defined in BaseClass or the the redefined one in DerivedClass? This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  36. Redefining Base Class Functions • Redefining function: function in a derived class that has the same name and parameter list as a function in the base class • Typically used to replace a function in base class with different actions in derived class

  37. Problem with Redefining BaseClass Object D invokes function X() In BaseClass. Function X() invokes function Y() in BaseClass, not function Y()in DerivedClass, because function calls are bound at compile time. This is static binding. void X(); void Y(); DerivedClass void Y(); DerivedClass D; D.X(); This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  38. What is binding? • Association of a ‘function definition’ to a ‘function call’ or an association of a ‘value’ to a ‘variable’, is called ‘binding’. • During compilation, every ‘function definition’ is given a memory address; as soon as function calling is done, control of program execution moves to that memory address and get the function code stored at that location executed, this is binding of ‘function call’  to ‘function definition’. • Binding can be classified as ‘static binding’ and ‘dynamic binding’. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  39. Static vs. Dynamic Binding • Static binding is done at compile time when a function is called in order to match it with the definition. (Early binding) • Eg.:overloaded function call, overloaded operators. • Dynamic binding is at run time where we can specify that the compiler matches a function call with the correct function definition at run time. (Late Binding) • Eg: Virtual function in C++, overridden methods in java. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  40. Polymorphism • Method Overriding • Using virtual functions • Method Overloading • Function Overloading • Operator Overloading This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  41. Virtual functions This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  42. Vtable and Vptr • To implement virtual functions, C++ uses a special form of late binding known as the virtual table. • The virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner. • The virtual table sometimes goes by other names, such as “vtable”, “virtual function table”, “virtual method table”, or “dispatch table”. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  43. The virtual table is actually quite simple, though it’s a little complex to describe in words. • First, every class that uses virtual functions (or is derived from a class that uses virtual functions) is given its own virtual table. This table is simply a static array that the compiler sets up at compile time. • A virtual table contains one entry for each virtual function that can be called by objects of the class. • Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  44. Second, the compiler also adds a hidden pointer to the base class, which we will call *__vptr. *__vptr is set (automatically) when a class instance is created so that it points to the virtual table for that class. • Unlike the *this pointer, which is actually a function parameter used by the compiler to resolve self-references, *__vptr is a real pointer. • Consequently, it makes each class object allocated bigger by the size of one pointer. It also means that *__vptr is inherited by derived classes, which is important. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  45. How it works? This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  46. Method overriding • When you derive a class, the derived class will inherit all the properties (state and behavior) of the base class. • If the derived class has different definition / implementation for the same named member function, then it is called method overriding. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  47. How Method overriding is achieved? • By Means of virtual functions • Virtual functions are used when a pointer to a base class object sometimes point to a base class and sometimes point to a derived class. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  48. When to use virtual? • If derived class’s member function and base class’s member function having the same name, • if the derived class’s function is to be called instead of the base class, then virtual keyword must be given in the base class’s member function. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  49. Why do we need virtual? • If you have ‘yes’ to any of these qns, you need to use virtual • Is Inheritance applied? • Is Method overriding needed?(derived class has different definition of a same named base class member function) • Is Pointers to the base class created? • Is Base class pointer points a derived class object? This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/.

  50. Declaring a virtual function class Derived:public Base { public : void setData() { ddata=20; } void dispData(); private: intddata; }; void Derived::dispData() { cout<<ddata; } class Base{ public : void setData() { bdata=0;} void dispData(); private: intbdata; }; void base::dispData() { cout<<bdata; } Int main() { Base *bptr; bptr=new Base; bptr->setData()l bPtr->dispData(); Bptr=new Derived; bptr->setData()l bPtr->dispData();

More Related