Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance and Run time Polymorphism

Similar presentations


Presentation on theme: "Inheritance and Run time Polymorphism"— Presentation transcript:

1 Inheritance and Run time Polymorphism
Sem III K.I.R.A.S

2 Inheritance Examples

3 Inheritance Examples

4 Inheritance Concept Polygon Rectangle Triangle class Rectangle{
private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Polygon Rectangle Triangle class Polygon{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); }; class Triangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); };

5 Inheritance Concept Polygon Triangle Rectangle
class Polygon{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; Triangle Rectangle class Rectangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area(); }; class Rectangle : public Polygon{ public: float area(); };

6 Inheritance Concept Polygon Triangle Rectangle
class Polygon{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; Polygon Triangle Rectangle class Triangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area(); }; class Triangle : public Polygon{ public: float area(); };

7 Inheritance Concept It is used to model the "is a" relationship. For example: Let human being be a class then we can derive child, male, female from this class .We say that child “is a “ kind of human being Let shape be a class the we can derive two classes from it : 2Dimensional shape and 3Dimensional shape. Then 2Dimensional shape “is a” kind of shape

8 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 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

9 Note: A base class pointer may address an object of its own class or an object of any class derived from that base class but a derived class pointer can address only the derived class object. It cannot hold the address of its base class. (Because if a pointer to a derived class object is allowed to address the base class object the compiler will expect members of the derived class to be in the base class also which is not possible). In general a pointer to a class at a particular level can be used as a pointer to objects of classes which are below that level in the class hierarchy. Any attempt to override this rule is treated as an error.

10 What is Overriding? Overriding happens in the context of inheritance. Function Overriding refers to modifying the definition of the base class method into the derived class with the same name and signature. Overriding only occurs in the context of the parent/child relationship .The type signatures must match. Overriding is resolved at run-time, not at compile time. In some languages (C++) overriding will only occur if the parent class has declared the method in some special way (example, keyword virtual). The type signatures are the same in both parent and child classes, and the method is declared as virtual in the parent class.

11 What is Overriding? There are actually two different ways that overriding can be handled: A replacement: which totally and completely replaces the code in the parent class the code in the child class. A refinement executes the code in the parent class, and adds to it the code in the child class. (Constructors, for example, almost always use refinement. ) There are a number of reasons to use replacement of methods. The method in the parent class is abstract, it must be replaced. The method in the parent class is a default method, not appropriate for all situations. The method in the parent can be more efficiently executed in the child.

12 overloading Can be either operator overloading or function overloading
Function overloading :Define several functions of the same name, differ by parameters. void Show() void Show(char *str) void show(int x) Must have different parameters int func1(int a, int b); double func1(int a, int b); void func(int value); void func(int &value); Overloading is resolved at compile time not at run time

13 Difference b/w overriding and overloading
Can be function overloading or operator overloading. Function overloading :Define several functions of the same name, differ by parameters. Can only involve functions .Function Overriding refers to modifying the definition of the base class method into the derived class with the same name and signature. Is resolved at compile time Is resolved at run time overloading can be done in one class for overriding there is necessary that at least two class should be present (base class and derived class)

14 The Student Class Hierarchy
DATA MEMBERS: student_id, year, name Member functions: print(), student inherits (isa) Postgraduate_student DATA MEMBERS: dept, thesis Member functions: print(),

15 The Student Class Hierarchy
void main() { student *ps; postgraduate_student *pgs; ps = &s1;//suppose s1 is object of student class cout << "\n ps, pointing to s1:"; ps->print(); ps = &g; //suppose g is object of postgraduate class cout << "\n ps, pointing to gs1:"; ps->print(); pgs = &g; //suppose g is object of postgraduate class cout << "\n pgs, pointing to gs1:"; pgs->print(); getch(); } student print() used. postgraduate_student print() used.

16 NOTE: The choice of print() depends on the pointer type, not the object pointed to. This is a compile time decision (called static binding).

17 Dynamic Binding in OOP X Print()
Classes X x; Y y; Z z; X *px; px = & ??; // can be x,y,or z px->print(); // ?? Y Print() Z Print()

18 Two Types of Binding Connecting a function call to a function body is called binding In c++ a function call can be bound to the actual function either at compile time or at run time, Resolving a function call at compile time is called compile time or early or static binding .Whereas resolving a function call at runtime is called runtime or late or dynamic binding Static Binding (the default in C++) px->print() uses X’s print this is known at compile time Dynamic Binding px->print() uses the print() in the object pointed at this is only known at run time coded in C++ with virtual functions

19 What is static binding? When binding is performed before the program is run (by the compiler and linker), it’s called early binding. (You may not have heard the term before because it’s never been an option with procedural languages: C compilers have only one kind of function call, and that’s early binding.)

20 What is Dynamic binding?
Dynamic binding allows applications to be written by invoking general methods via a base class pointer class Base { public: virtual int vf (void); }; Base *bp = /* pointer to a subclass */; bp->vf (); However, at run-time this invocation actually invokes more specialized methods implemented in a derived class, e.g., class Derived : public Base { public: virtual int vf (); }; Derived d; bp = &d; bp->vf (); // invokes Derived::vf()

21 What is Dynamic binding
Late binding, which means the binding occurs at runtime, based on the type of the object. Late binding is also called dynamic binding or runtime binding. When a language implements late binding, there must be some mechanism to determine the type of the object at runtime and call the appropriate member function. In the case of a compiled language, the compiler still doesn’t know the actual object type, but it inserts code that finds out and calls the correct function body. The late-binding mechanism varies from language to language, but you can imagine that some sort of type information must be installed in the objects

22 Which to use when When to chose use different bindings
– Static Binding Use when you are sure that any subsequent derived classes will not want to override this operation dynamically (just redefine/hide) Use mostly for reuse – Dynamic Binding Use when the derived classes may be able to provide a different (e.g., more functional, more efficient) implementation that should be selected at run-time .Used to build dynamic type hierarchies & to form “abstract data types”

23 Virtual functions Virtual functions allow the programmers to declare functions in a base class, which can be defined in each base class. A pointer to an object of a base class can also point to the objects of its derived classes . In this case a member function to be invoked depends on the class’s object to which the pointer is pointing. When a call to any object is made using the same interface (irrespective of object to which the pointer variable is pointing) ,the function relevant to that object will be selected at run time syntax: virtual return-type functionname(argument list) { }

24 Virtual functions The virtual function allows one type to express its distinction from another, similar type, as long as they’re both derived from the same base type. This distinction is expressed through differences in behavior of the functions that you can call through the base class. To cause late binding to occur for a particular function, C++ requires that you use the virtual keyword when declaring the function in the base class. Late binding occurs only with virtual functions, and only when you’re using an address of the base class where those virtual functions exist, although they may also be defined in an earlier base class. To create a member function as virtual, you simply precede the declaration of the function with the keyword virtual. Only the declaration needs the virtual keyword, not the definition.

25 Virtual functions It is important to note that virtual functions have to be accessed through a pointer to the base class. It is to be remembered that runtime polymorphism is achieved only when a virtual function is accessed through a pointer to the base class. Only class member functions can be declared as virtual functions .Regular functions and friend functions do not qualify as virtual functions

26 How C++ implements late binding
All the work goes on behind the scenes by the compiler, which installs the necessary late-binding mechanism when you ask it to (you ask by creating virtual functions). The keyword virtual tells the compiler it should not perform early binding. Instead, it should automatically install all the mechanisms necessary to perform late binding. To accomplish this, the typical compiler creates a single table (called the VTABLE) for each class that contains virtual functions. The compiler places the addresses of the virtual functions for that particular class in the VTABLE.

27 How C++ implements late binding
In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object. When you make a virtual function call through a base-class pointer (that is, when you make a polymorphic call), the compiler quietly inserts code to fetch the VPTR and look up the function address in the VTABLE, thus calling the correct function and causing late binding to take place. All of this – setting up the VTABLE for each class, initializing the VPTR, inserting the code for the virtual function call – happens automatically, so you don’t have to worry about it. With virtual functions, the proper function gets called for an object, even if the compiler cannot know the specific type of the object.

28 Virtual functions class Shape { public: double x, y;
virtual void draw(); }; class Line : public Shape { void draw(); class Arc : public Shape { Shape *dl[10]; dl[0] = new Line; dl[1] = new Arc; dl[0]->draw(); // invoke Line::draw() dl[1]->draw(); // invoke Arc::draw()

29 Picturing Virtual functions
VTABLEs objects Array of shape pointers Shape *dl[10] &Line::draw Line object vptr Arc object vptr &Arc::draw

30 Virtual functions The array of shape pointers has no specific type information; they each point to an object of type shape. Line, Arc ( all fit into this category because they are derived from shape and thus have the same interface as shape, and can respond to the same messages) However, the compiler doesn’t know that they are anything more than shape objects, so it would normally call the base-class versions of all the functions. But in this case, all those functions have been declared with the virtual keyword, so something different happens.

31 Virtual functions Each time you create a class that contains virtual functions, or you derive from a class that contains virtual functions, the compiler creates a unique VTABLE for that class, seen on the right of the diagram. In that table it places the addresses of all the functions that are declared virtual in this class or in the base class.


Download ppt "Inheritance and Run time Polymorphism"

Similar presentations


Ads by Google