Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică."— Presentation transcript:

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

2 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.

3 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

4 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

5 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(); }

6 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!

7 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

8 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) { // … }

9 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? }

10 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* }

11 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.

12 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.”; }

13 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!

14 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.”; }

15 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]


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

Similar presentations


Ads by Google