Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

Chapter 1 OO using C++. Abstract Data Types Before we begin we should know how to accomplish the goal of the program We should know all the input and.
V IRTUAL F UNCTIONS Chapter 10 Department of CSE, BUET 1.
12/08/08MET CS Fall Polymorphism 10. Polymorphism Goal: Goal: Create methods that can be invoked with all object types, base as well as.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
LECTURE 8. Polymorphism One interface, multiple methods C++ supports both compile time and runtime polymorphism.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Pointer Data Type and Pointer Variables
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
C++ Review Classes and Object Oriented Programming Parasol Lab, Texas A&M University.
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
Inheritance Session 5 Object Oriented Programming with C++/ Session 5/ 1 of 41.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Overview of C++ Polymorphism
OBJECT ORIENTED PROGRAMMING. Design principles for organizing code into user-defined types Principles include: Encapsulation Inheritance Polymorphism.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
A First Book of C++ Chapter 12 Extending Your Classes.
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
Memory Management.
Constructors and Destructors
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Andy Wang Object Oriented Programming in C++ COP 3330
Polymorphism &Virtual Functions
Class A { public : Int x; A()
Object-Oriented Programming
Inheritance & Polymorphism
Introduction to Classes
Polymorphism & Virtual Functions
Polymorphism Lec
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Introduction to Classes
Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes
Virtual Functions Department of CSE, BUET Chapter 10.
Polymorphism Polymorphism
Constructors and Destructors
CISC/CMPE320 - Prof. McLeod
9-10 Classes: A Deeper Look.
Overview of C++ Polymorphism
VIRTUAL FUNCTIONS RITIKA SHARMA.
9-10 Classes: A Deeper Look.
C++ Object Oriented 1.
Presentation transcript:

Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6

Object Oriented Programming with C++ / Session 6 / 2 of 44 Session Objectives n Describe Multiple Inheritance Constructors under Multiple Inheritance Ambiguity in Multiple Inheritance Multiple Inheritance with a Common Base n Describe Virtual Base Classes Constructors and Destructors n Use Pointers to Objects to access Member Functions

Object Oriented Programming with C++ / Session 6 / 3 of 44 Session Objectives(Contd.) n Describe Virtual functions n Describe Polymorphism n Describe Dynamic binding n Describe Pure Virtual Functions n Describe Abstract classes n Describe Virtual destructors

Object Oriented Programming with C++ / Session 6 / 4 of 44 Multiple Inheritance n Multiple inheritance is the process of creating a new class from more than one base class. The derived class inherits the properties of two or more base classes. n Multiple inheritance can combine the behaviour of many base classes in a single class. n A multiple inheritance hierarchy represents a combination of its base classes.

Object Oriented Programming with C++ / Session 6 / 5 of 44 Multiple Inheritance (Contd.) StudentTeacher Teaching assistant Base class Derived class

Object Oriented Programming with C++ / Session 6 / 6 of 44 Multiple Inheritance (Contd.) n The syntax for multiple inheritance is similar to that for single inheritance. class Teacher { }; class Student { }; class Teach_asst: public Teacher, public Student The names of both the base classes are provided separated by a comma. The rules of inheritance and access for multiple inheritance are the same as for single inheritance.

Object Oriented Programming with C++ / Session 6 / 7 of 44 Constructors class Teacher{ private: int x; public: Teacher(){x =0;}//constructors Teacher(int s){x = s;} }; class Student{ private: int y; public: Student(){y = 0;}//constructor Student(int a){y = a;} };

Object Oriented Programming with C++ / Session 6 / 8 of 44 Constructors (Contd.) class Teach_asst: public Teacher,public Student { private: int z; public: Teach_asst():Teacher(),Student() //constructor {z = 0;} Teach_asst(int s,int a,int b): Teacher(s),Student(a) {z = b;} };

Object Oriented Programming with C++ / Session 6 / 9 of 44 Constructors (Contd.) n Constructors have to be defined to initialise the data members of all classes. n The names of the base class constructor follow the colon and are separated by commas: Teach_asst():Teacher(),Student(); n If the constructors had arguments then: Teach_asst(int s, arg for Teacher class int a, arg for Student class int b): arg for this class Teacher(s), call Teacher constructor Student(a) call Student constructor {z = b;} set own data member

Object Oriented Programming with C++ / Session 6 / 10 of 44 Constructors and Destructors n General order for calling Constructors: Base classes as they appear in the list of base classes: Teacher, Student If there are member objects in the class, they are initialised next, in the order they appear in the derived class declaration. The object itself (using the code in its constructor). n General order for calling Destructors: The destructor of the class is called first, then those of member objects, and then the base classes.

Object Oriented Programming with C++ / Session 6 / 11 of 44 Ambiguity in Multiple Inheritance n Compiler will not be able to understand which function to use if two base classes have the same function or data member name. class Alpha{ public: void display(); }; class Beta{ public: void display() }; class Gamma: public Alpha,public Beta { };

Object Oriented Programming with C++ / Session 6 / 12 of 44 Ambiguity (Contd.) void main() { Gamma obj; obj.display();//ambiguous: cannot be compiled } n To access the correct function or data member you will need to use the scope resolution operator. obj.Alpha::display(); obj.Beta::display();

Object Oriented Programming with C++ / Session 6 / 13 of 44 Ambiguity (Contd.) n It is upto the programmer to avoid such conflicts and ambiguities. Can be resolved by defining a new function display() in the derived class: void Gamma::display() { Alpha::display(); Beta::display(); } The compiler is able to detect the name clashes and resolves it.

Object Oriented Programming with C++ / Session 6 / 14 of 44 Multiple Inheritance: Common Base n There are many combinations which inheritance can be put to. n There is the possibility of having a class as a base twice. StudentTeacher Teaching assistant Person

Object Oriented Programming with C++ / Session 6 / 15 of 44 Common Base n Both Teacher and Student contain a copy of the Person class members. When Teaching assistant is derived from both Teacher and Student it contains two copies of the Person class members - one from Teacher and one from Student. This gives rise to ambiguity between the base class data members. n Another problem is that declaring an object of class Teaching assistant will invoke the Person class constructor twice.

Object Oriented Programming with C++ / Session 6 / 16 of 44 Virtual Base Classes n Multiple inheritance hierarchies can be complex, and may lead to a situation in which a derived class inherits multiple times from the same indirect class.

Object Oriented Programming with C++ / Session 6 / 17 of 44 Example class window{ protected: int basedata; }; class border: public window { }; class menu: public window { }; class border_and_menu: public border, public menu { public: int show() {return basedata;} };

Object Oriented Programming with C++ / Session 6 / 18 of 44 Virtual Base Classes (Contd.) When the classes menu and border are derived from window, each inherits a copy of window. This copy is called a subobject. Each subobject contains its own copy of basedata from the class window. When class border_and_menu refers to basedata the compiler does not know which copy is being accessed and hence the error occurs.

Object Oriented Programming with C++ / Session 6 / 19 of 44 Virtual Base Classes (Contd.) n To avoid two copies of the base class we use a virtual base class. n To make a base class virtual include the keyword virtual when listing the base class in the derived class declaration. class border: virtual public window { }; and class menu: virtual public window { }; Useful to avoid unnecessary repetitions of the same data member in a multiple inheritance hierarchy.

Object Oriented Programming with C++ / Session 6 / 20 of 44 Virtual Base Classes (Contd.) n Virtual base class is represented by a single object of the class. n Note the difference with normal multiple inheritance.

Object Oriented Programming with C++ / Session 6 / 21 of 44 Constructors and Destructors n Presence of virtual base classes changes the order in which constructors are called. A virtual base class is initialised before any non-virtual base class. If there is more than one virtual base class, the order of initialisation is determined by their position in the inheritance graph from top to bottom and left to right. n The call for the destructor follows the same rules, but in the reverse order.

Object Oriented Programming with C++ / Session 6 / 22 of 44 Pointers to Objects n Pointers can point to objects as well as to simple data types. Base* ptr; ptr = new Base; To refer to member functions in the object pointed to by ptr we cannot use a dot operator. The dot operator requires the identifier on its left to be a variable. Since ptr is a pointer the arrow operator (->) is used to access a member function, ptr->show();

Object Oriented Programming with C++ / Session 6 / 23 of 44 Virtual functions n A virtual function is a function that does not really exist but does affect some parts of a program. Consider a program to draw different shapes like triangles, circles, squares, ellipses etc. Consider that each of these classes has a member function draw() by which the object is drawn.

Object Oriented Programming with C++ / Session 6 / 24 of 44 Example class Shapes{ public: void draw()//function in the base class {cout<<"Draw Base\n";} }; class circle: public Shapes{ private: int radius; public: void draw()//redefined in derived class {cout<<"Draw circle";} };

Object Oriented Programming with C++ / Session 6 / 25 of 44 Example(Contd.) class square: public Shapes{ private: int length; public: void draw()//redefined in derived class {cout<<"Draw square";} }; void main(){ circle c; square s; Shapes* ptr; ptr = &c; ptr->draw(); ptr = &s; ptr->draw(); }

Object Oriented Programming with C++ / Session 6 / 26 of 44 Virtual functions(Contd.) n The address of the derived class object is assigned to a pointer of the base class: ptr = &c;//c is an object of class circle n When we call the draw() function using, ptr->draw(); we expected that the draw() function of the derived class would be called. n Result of the program: Draw Base

Object Oriented Programming with C++ / Session 6 / 27 of 44 Virtual functions(Contd.) We want to be able to use the function call to draw a square or any other object depending on which object ptr points to. i.e. different draw() functions should be executed by the same function call. All the different classes of shapes must be derived from a single base class Shapes. The draw() function must be declared to be virtual in the base class. n It can then be redefined in each derived class.

Object Oriented Programming with C++ / Session 6 / 28 of 44 Virtual functions(Contd.) class Shapes{ public: virtual void draw()//virtual in the base class {cout<<"Draw Base\n";} }; n A virtual function allows derived classes to replace the implementation provided by the base class. n The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class.

Object Oriented Programming with C++ / Session 6 / 29 of 44 Virtual functions(Contd.) n With the virtual function, the result is: Draw circle Draw square The same function call, ptr->draw(); executes different functions depending on the contents of ptr.

Object Oriented Programming with C++ / Session 6 / 30 of 44 Points to be noted n Virtual function should be declared in the base class and cannot be redeclared in a derived class. Return type of a member function must follow the keyword virtual. n If a hierarchy of derived classes is used, the virtual function has to be declared in the top-most level.

Object Oriented Programming with C++ / Session 6 / 31 of 44 Points to be noted (Contd.) n A virtual function must be defined for the class in which it was first declared. n Redefined function in the derived class must have the same parameters (same number and data type), otherwise the compiler thinks you want to overload the virtual function. The return type does not have to match.

Object Oriented Programming with C++ / Session 6 / 32 of 44 Polymorphism n "poly" means "many" in Greek and "morphism" means "form". n "polymorphism" means "many forms". n It is the process of defining a number of objects of different classes in a group and using different function calls to carry out the operations of the objects. n It means, "to carry out different processing steps by functions having the same messages".

Object Oriented Programming with C++ / Session 6 / 33 of 44 Polymorphism (Contd.) For example: Class mammals: Different mammals have different responses to the function EAT. The object will perform the action that is most appropriate for it. Objects are polymorphic if they have some similarities but are still somewhat different. n The facility to invoke an appropriate function from any of the given classes using the pointer of the base class is a form of polymorphism. E.g.. Using virtual functions.

Object Oriented Programming with C++ / Session 6 / 34 of 44 Dynamic binding n Non-virtual member functions are selected statically (at compile-time) based on the type of the pointer (or reference) to the object. n Virtual member functions are resolved dynamically (at run-time). i.e., member function is selected at run-time based on the type of the object, not the type of the pointer/reference to that object. n Dynamic binding : The address of the code in a member function invocation is determined at the last possible moment, based on the dynamic type of the object at run time.

Object Oriented Programming with C++ / Session 6 / 35 of 44 Dynamic binding (Contd.) n Requires some overhead in processing but provides increased power and flexibility in programming. n Dynamic binding is a result of virtual functions. If the keyword virtual is used with the function declaration in the base class, the system will use dynamic binding else static binding will be used.

Object Oriented Programming with C++ / Session 6 / 36 of 44 Pure Virtual functions n Some classes such as class Shapes, represent abstract concepts for which objects cannot exist. It is not possible to provide concrete definitions for its virtual functions that will actually create a Shape object. n Alternative: Declare the virtual function of the class Shape as a pure virtual function. n A pure virtual function has only a function declaration. n It is declared by assigning the value of zero to the function as in, virtual void getdata() = 0;

Object Oriented Programming with C++ / Session 6 / 37 of 44 Pure Virtual functions (Contd) n Every derived class must include a function definition for each pure virtual function that is inherited from the base class if it has to be used to create an object. n This assures that there will be a function available for each call. n Cannot create an object of any class, which contains one or more pure virtual functions, because there is nothing to answer if a function call is sent to the pure virtual method.

Object Oriented Programming with C++ / Session 6 / 38 of 44 Abstract Classes n A class containing one or more pure virtual functions cannot be used to define an object--called an abstract class. n Only useful as a base class to be inherited into a useable derived class. n No objects of an abstract class can be created. n Abstract class can only be used as a base for another class.

Object Oriented Programming with C++ / Session 6 / 39 of 44 Abstract Classes - Example class Shapes{ public: virtual void draw() = 0; //pure virtual function virtual void rotate(int) = 0; //pure virtual function }; class circle: public Shapes{ private: int radius; public: circle(int r); void draw(); void rotate(int){ } };

Object Oriented Programming with C++ / Session 6 / 40 of 44 Abstract Classes(Contd.) n If a class inherits an abstract class without providing a definition for the pure virtual function, then it too becomes an abstract class and cannot be used to define an object. Important use of abstract classes is to provide an interface without exposing any implementation details. Used in many commercially available libraries and in application frameworks.

Object Oriented Programming with C++ / Session 6 / 41 of 44 Virtual destructors n Destructor of derived class is not invoked to free the memory storage that was allocated by the constructor of the derived class. n This is because destructors are non-virtual and the message will not reach the destructors under dynamic binding. n Better to have a virtual destructor function to free memory space effectively under dynamic binding.

Object Oriented Programming with C++ / Session 6 / 42 of 44 Example class Alpha{ private: char* alpha_ptr; public: Alpha()//constructor cannot be virtual {alpha_ptr = new char[5];} virtual void fn();//virtual member function virtual ~Alpha()//virtual destructor {delete[] alpha_ptr;} };

Object Oriented Programming with C++ / Session 6 / 43 of 44 Example (Contd.) class Beta: public Alpha{ private: char* ptrderived; public: Beta() {ptrderived = new char[100];} ~Beta() {delete[] ptrderived;} }; void main() { Alpha *ptr = new Beta; delete ptr; }

Object Oriented Programming with C++ / Session 6 / 44 of 44 Virtual destructors (Contd.) n Virtual functions bind to the code associated with the class of the object, rather than with the class of the pointer/reference. When you say delete ptr, and the base class has a virtual destructor, the destructor that gets invoked is the one associated with the type of the object *ptr, rather than the one associated with the type of the pointer. n As a derived class instance always contains a base class instance, it is necessary to invoke destructors of both the classes in order to ensure that all the space on the heap is released.