Run Time Type Information, Binary files. RTTI – why? Problem: Up-casting works fine. –Treating sub-class as base class Shape * s = new Circle(); What.

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick The Programming Process rUse an editor to create a program file (source file). l contains the text of.
Advertisements

This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 2:
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
CIS 101: Computer Programming and Problem Solving Lecture 8 Usman Roshan Department of Computer Science NJIT.
Polymorphism, Virtual Methods and Abstract Classes.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
CS1061 C Programming Lecture 4: Indentifiers and Integers A.O’Riordan, 2004.
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
. 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.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Run-Time Type Identification Jim Fawcett CSE687 – Object Oriented Design Spring 2007.
CS 192 Lecture 3 Winter 2003 December 5, 2003 Dr. Shafay Shamail.
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  Due to poor understanding of the problem and solution.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Templates ~ their instantiation and specialization.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Operator Overloading & Exception Handling TCP1201 OOPDS 1 Lecture 5 1.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
1 Streams In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
Looping and Counting Lecture 3 Hartmut Kaiser
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Chapter 9 Questions 1. What are the difference between constructors and member functions? 2. Design and implement a simple class as you want, with constructors.
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Pointers *, &, array similarities, functions, sizeof.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Inheritance and Composition Reusing the code and functionality Unit - 04.
Lecture 01a: C++ review Topics: Setting up projects, main program Memory Diagrams Variables / Types (some of) the many-types-of-const's Input / Output.
Friend classes Friend class methods Nested classes Throwing exceptions, try blocks and catch blocks Exception classes Runtime type identification (RTTI)
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
Object Oriented Programming Elhanan Borenstein Lecture #7.
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Exception Handling How to handle the runtime errors.
Expressions Version Topics Arithmetic expressions Conversions Operator precedence String class 2.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
Overview Working directly with memory locations is beneficial. In C, pointers allow you to: change values passed as arguments to functions work directly.
Yan Shi CS/SE2630 Lecture Notes
C++ Lesson 1.
Inheritance.
Polymorphism, Virtual Methods and Abstract Classes
c++ style casting At the beginning c++ supported two styles of casts:
Data types Data types Basic types
7. Inheritance and Polymorphism
Writing and Reading Raw Data
Advanced Program Design with C++
Inheritance.
Student Book An Introduction
Computer Programming Methodology File Input
Reserved Words.
Programming with ANSI C ++
Chapter 15 Pointers, Dynamic Data, and Reference Types
Polymorphism.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers.
Hank Childs, University of Oregon
Prof. Bhushan Trivedi Director GLS Institute of Computer Technology
Pointer Operations.
Type Conversion It is a procedure of converting one data type values into another data type In C programming language we are having two types of type conversion.
Presentation transcript:

Run Time Type Information, Binary files

RTTI – why? Problem: Up-casting works fine. –Treating sub-class as base class Shape * s = new Circle(); What about down-casting? –might not be safe ! –correctness cannot be determined by the compiler. Circle * c = (Circle*) s; Shape Line Circle

RTTI RTTI – Run Time Type Information Mechanisms for RTTI: 1.dynamic_cast operator 2.typeid operator (and type_info class)

The ‘dynamic_cast‘ operator dynamic_cast (expression) u Enables run-time type checking:  returns a valid pointer if “expression” is of type “T”  Null pointer 0 otherwise u Cast of a reference type throws an exception when it fails (“bad_cast”)

Dynamic_cast : example Shape* s = container.pop(); Circle* c = dynamic_cast (s); if (c) { // c is a circle c->doSomething(); else handle(); //handle unexpected event Note: the actual type of “ s ” is not mentioned! –Can be any sub-class of Circle.

Example Shape s; Circle c; Line l; ThinLine tl; Shape* arr[4] = {&s, &c, &l, &tl}; for ( int i=0; i<3; i++ ) { Line * pl = dynamic_cast ( arr[i] ); pc? cout << “cast ok\n” : cout << “cast fail\n”; } Shape LineCircle Output: cast fail // Shape to Line cast fail // Circle to Line cast ok // Line to Line cast ok // ThickLine to Line ThickLine

dynamic_cast - more dynamic_cast (expression) Note: u Used only on pointer or reference types. u Can be used for up-cast, down-cast u and also for cross-cast (out of this scope) u Only for types with virtual-functions (“Polymorphic types”) u These object have a space for the information about the type: the virtual function table

dyn_cast: only for polymorphics void foo(Shape * s, Time * t) { Circle * c = dynamic_cast ( s ); //ok Date * date = dynamic_cast ( t ); //error } class Circle : public Shape { virtual void draw(); … } class Date : public Time { …// Time has no virtual functions }

Static Cast Used when the compiler cannot assume anything about the memory pointed to by a void*. This implies that dynamic cast cannot cast from a void*. For that, a static cast is needed. R* f(void *p) { S ps = static_cast (p); } //trust the programmer.

RTTI : typeid operator Obtains info about an object/expression usage: typeid( obj ) (like “sizeof”) Example: Dog d; Cat c; cout << “d is a “ << typeid(d).name() << “,” << “c is a “ << typeid(c).name() <<endl; Output: d is a Dog, c is a Cat typeid() returns a reference to a standard library type called type_info defined in.

type_info class typeid(expression) returns an object of the type_info class. e.g. type_info& ti = typeid(d); class type_info { public: bool operator==( type_info const&)const; char const* name() const; … private: type_info( type_info const&); //prevent copying type_info& operator=( type_info const& ); }

RTTI misuse void rotate( shape const& s ) { if (typeid(s) == typeid(Circle) ) //do nothing else if (typeid(s) == typeid(Triangle) ) //rotate Triangle else if (typeid(s) == typeid(Rectangle) ) //rotate Rectangle … } Use virtual functions (polymorphism) when you can ! VERY common misuse of RTTI

Binary files

Leading example: image files Images are stored as matrices of numbers (Pixels). Here, we deal with gray-scale images (“black and white”) 8 bits per pixel –i.e. each pixel between 0 and is white, 255 is black, others are gray

storing images How can we store images on files? For each image we want to store: –width//integer –height//integer –number of bits per pixel//short –the pixels//matrix of integers Requirements: read/write easily, save space, save computation, etc.

storing images First try: text files (like you did so far) width = 3 height = 2 bits_per_pixel = 8 255, 0, 0 0,255,100 “myImg.txt” cons: u long u needs parsing (e.g. atoi for numbers) pros: u readable by humans u easy to edit u but who handles images like that?

Binary files Better solution: Binary files u Save the data the way the computer holds it pros: u Smaller u No parsing (faster) u Widely used ! u For example: BMP files, other data cons: u hard to read for humans u Machine dependant

Images as binary files width 2 bytes [0,…,0,0,1,1] height 2 bytes [0,…,0,0,1,0]

Images as binary files bits per pixel 1 byte [0,0,0,0,1,0,0,0]

Images as binary files pixel 1 byte [1,1,1,1,1,1,1,1] pixel 1 byte [0,0,0,0,0,0,0,0]

Binary files bits per pixel now value 16

Example: writing a binary file Pixel pixs[30]; int width = 100, height = 150; short bitsPerPix = 16; binary open for writing ofstream outfile; outfile.open(“pic.raw", ios::bin | ios::out); outfile.write(&width, sizeof(int)); outfile.write(&height, sizeof(int)); outfile.write(&bitsPerPix, sizeof(short)); outfile.write(pixs, 30*sizeof(Pixel)); outfile.close(); ostream& write( char const* str, streamsize n);

Learn by yourselves: c++ casting (see slides ahead and Stroustrup 15.4 and more)

c++ style casting At the beginning c++ supported two styles of casts: –(typename)expression –typename(expression) Instead there are now four new casting operators: –static_cast (expression) –const_cast (expression) –reinterpret_cast (expression) –dynamic_cast (expression)

The 'static_cast operator Works where implicit conversion exists –standard or user-defined conversion –up-casts Safer that “old-style” casts –e.g. won’t cast int* to float* Failure causes a compiler error –No dynamic checking is done! int i = static_cast (12.45); static_cast (expression)

The ‘const_cast'operator Is used to remove (or add) const -ness: void g(C * cp); void f(C const* cp) { g(const_cast (cp)); } Usually, you should design your variables/methods such that you won’t have to use const_cast. Failure causes compiler errors const_cast (expression)

‘ reinterpret_cast'operator Is used to reinterpret byte patterns. double d(10.2); char* dBytes = reinterpret_cast (&d); Circumvents the type checking of c++. Very implementation-dependent. Rarely used. !Very dangerous ! reinterpret_cast (expression)