Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.

Slides:



Advertisements
Similar presentations
Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
Advertisements

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
. Plab – Tirgul 11 RTTI, Binary files. RTTI – why? Problem: u Up-casting works fine.  Treating sub-class as base class Shape * s = new Circle(); u What.
Run-time type information (RTTI) and casts Consider classes for components and windows: class Component {... virtual void draw() {} }; class Window: public.
Run Time Type Information, Binary files. RTTI – why? Problem: Up-casting works fine. –Treating sub-class as base class Shape * s = new Circle(); What.
1 CSE 303 Lecture 24 Inheritance in C++, continued slides created by Marty Stepp
C++ fundamentals.
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.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 12: Adding Functionality to Your Classes.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Run-Time Type Identification Jim Fawcett CSE687 – Object Oriented Design Spring 2007.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
Static and Dynamic Behavior CMPS Power of OOP Derives from the ability of objects to change their behavior dynamically at run time. Static – refers.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
1 Inheritance We are modeling the operation of a transportation company that uses trains and trucks to transfer goods. A suitable class hierarchy for the.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object Oriented Software Development
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
Inheritance and Composition Reusing the code and functionality Unit - 04.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Friend classes Friend class methods Nested classes Throwing exceptions, try blocks and catch blocks Exception classes Runtime type identification (RTTI)
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Object Oriented Programming Elhanan Borenstein Lecture #7.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
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,
CSCI-383 Object-Oriented Programming & Design Lecture 17.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
Modern Programming Tools And Techniques-I
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
7. Inheritance and Polymorphism
Polymorphism & Virtual Functions
INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING (OOP) & CONCEPTS
Comp 249 Programming Methodology
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Programming with ANSI C ++
Java Programming Language
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Presentation transcript:

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică

2Programming IIObject Oriented Programming Type Checking DEFINITION [Type system] A type system defines how a programming language classifies values and expressions into types, how it manipulates those types and they interact. DEFINITION [Type checking] The process of verifying and enforcing the constraints defined in a type system. Classification of type systems/checking: –Static typing: compile-time (syntactic) (e.g. C++, Java, ML) –Dynamic typing: run time (operational) (e.g. LISP) C++ is a statically typed programming language Nevertheless, it supports polymorphism, i.e. the ability of code (in particular, functions or classes) to act on values of multiple types, or to the ability of different instances of the same data-structure to contain elements of different types.

3Programming IIObject Oriented Programming References DEFINITION [Reference] A reference is an alternative (alias) name for an object. [Stroustrup, 1997 – Section 5.5] Main use: –Specifying arguments for functions –Specifying return values for functions Used mainly for operator overloading Syntax: X& ref; // reference to type X A reference must be initialized! Common implementation of references is as constant pointer that is dereferenced each time it is used. Examples: void f() { int i = 1; int& r = i; // r and I refer to the same int int& r2; // ERROR: initializer is missing int x = r; // x = 1 r = 2; // in fact, i = 2 int* p = &r; // p points to i } 1 i r void increment(int& i) { i++; } void f() { int a = 5; increment(a); // a=6 } Memory representation

4Programming IIObject Oriented Programming RTTI Agenda Run-time type information (RTTI) Introduction Dynamic casting Static casting vs. dynamic casting Typeid and extended type information Uses and misuses of RTTI

5Programming IIObject Oriented Programming Introduction DEFINITION [RTTI] The use of type information at run-time is referred as “run-time type information” (RTTI). DEFINITION [upcast, downcast, crosscast] Casting from base to derived class is called downcast. Casting from derived to base is called upcast. Casting from a base to a sibling base is called crosscast. Recover the “lost” type of an object Example: Employee Manager Temporary Consultant voif f(Temporary* pt) { // crosscast Employee* pe = dynamic_cast (pt); if(pe) pe->print(); }

6Programming IIObject Oriented Programming Dynamic casting Syntax: class C : public A, private B { }; void f(C* pc) { B* pb1 = pc; // error: B is a private base B* pb2 = dynamic_cast (pc); // => NULL } dynamic_cast (p) where, T – a type, p – a pointer or reference Usage for upcast not necessary doesn’t allow the violation of protection of private and protected base classes. Usage for downcasting and crosscasting: if the object pointed by p is not NULL and is of class T or has a unique base class of type T, then dynamic_cast returns a pointer of type T* of that type; othewise returns 0 the type of pointer p has to be a polymorphic type, otherwise 0 is returned. T- doesn’t have to be polymorphic always test the result against 0 value!

7Programming IIObject Oriented Programming Implementation of dynamic_cast If RTTI is enabled, then a pointer to type information object (tye_info) is stored in the VFT (Virtual Function Table) attached to a polymorphic type type_info object contains the list of base classes dynamic_cast simply compares the type_info objects representing the base classes

8Programming IIObject Oriented Programming Dynamic casting and references If p is pointer then an error is signaled with a NULL (0) value. This is not feasible if p is a reference! A bad_cast exception is thrown. voif f(Temporary& rt) { try { Employee& re = dynamic_cast (rt); re.print(); } catch(bad_cast) { // … }

9Programming IIObject Oriented Programming Dynamic casting and multiple inheritance Multiple inheritance: pay attention to base classes that appears more than once in a diamond- like inheritance. See example below: class Storable { } ; class Component : public virtual Storable { }; class Receiver : public Component { }; class Transmitter : public Component { }; class Radio : public Receiver, public Transmitter { }; void f(Radio& r) { Storable* ps = &r; Component* pc = dynamic_cast (ps); // => 0; which Component? of Receiver or Transmitter? }

10Programming IIObject Oriented Programming Static casting vs. dynamic casting static_cast does not examine the object it cast from, while dynamic_cast does! static_cast does not require a polymorphic object. static_cast does not make any checking; dynamic_cast checks the cast to be valid. dynamic_cast can cast from a polymorphic virtual base to derived / sibling class, but static_cast cannot do this because it doesn’t examine the object it cast from. void f(Radio& r) { Receiver* pr = &r; // ok Radio* pradio = static_cast (pr); // ok, unchecked pradio = dynamic_cast (pr); // ok, checked at run-time Storable* ps = &r; // Storable is virtual base of Radio pradio = static_cast (ps); // error: cannot cast from virtual base pradio = dynamic_cast (ps); // ok, run-time checked } void g(void* p) { Radio* pr = static_cast (p); // trust the programmer pr = dynamic_cast (p); // error: void is not polymorphic => dynamic_cast can’t be used to cast from void* }

11Programming IIObject Oriented Programming Remarks Both, static & dynamic casts respect const and access controls. Examples: class C : public A, private B { }; void f(C* pc, const A* pa) { B* pb1 = pc; // error: B is a private base B* pb2 = dynamic_cast (pc); // => NULL B* pb3 = static_cast (pc); // error static_cast (a); // error: can’t cast away const dynamic_cast (a); // error: can’t cast away const A* ppa = const_cast (a); // OK } Calling virtual functions or accessing run-time type information from constructors is not wise because the object is not completely constructed at that point and its real/final type is not yet known.

12Programming IIObject Oriented Programming Typeid Sometimes is important to know the exact type of an object (class name) typeid operator serves this scope by returning an object representing the type of its operand, i.e. a const reference to a type_info. if the operand is NULL it throws a bad_typeid exception. type_info class exposes the following interface: operator== and operator!= – allows comparision of types; name() – returns the name of the type; before(type_info&) – allow to sort type_info Usually, there are more than one instance of type_info objects for a single class (type)! The character representation of the type name is implementation-dependent. Example: void f(Shape* ps, Shape& rs) { cout << “Shape type is: ” << typeid(rs).name(); if(typeid(*ps) == typeid(rs)) cout << “The same type.”; }

13Programming IIObject Oriented Programming Misuses of RTTI void f(Shape* ps) { if(typeid(*ps) == typeid(Circle)) // actions for Circle else if(typeid(*ps) == typeid(Triangle)) // actions for Triangle // etc. } Don’t abuse of type information; rely on polymorphism implemented using virtual functions whenever possible! NOT THIS WAY!! class Object { }; class Container : public Object { public: void put(Object *); Object* get(int idx); }; class My : public Object { } ; My f(My* p, Container* c) { c->put(p); Object* po = c->get(12); if( My* p1 = dynamic_cast (po) ) return p1; } NOT THIS WAY!! HOMEWORK: Re-write these two examples in a more suitable form!

14Programming IIObject Oriented Programming Uses of RTTI Extend class functionality without changing existing class because either is not accessible (for example, a class from an external library) or changing the class implies a lot of changes in other classes as well (for example, adding dummy functions). Implementation of a simple I/O system. void read_file(istream& is) { IOobject* p = getObject(is); if( Shape* shape = dynamic_cast (p) ) { shape->draw(); } else if( Layout* layout = dynamic_cast (p)) { canvas->setLayout(layout); } else cout << “Invalid object found in file.”; }

15Programming IIObject Oriented Programming Further Reading [Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Chapter 13, 15.4][Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Chapter 13, 15.4]