Dr. Md. Humayun Kabir CSE Department, BUET

Similar documents
CS OBJECT ORIENTED PROGRAMMING

W3101: Programming Languages C++ Ramana Isukapalli

Where do we stand on inheritance?

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

C++ Programming: Polymorphism

C++ Casts and Run-Time Type Identification

C++ Exception Handling. Dr. Md. Humayun Kabir CSE Department, BUET

TPF Users Group Spring 2005

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns

OBJECT ORIENTED PROGRAMMING USING C++

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Increases Program Structure which results in greater reliability. Polymorphism

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

G52CPP C++ Programming Lecture 15

Variables. Data Types.

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Tokens, Expressions and Control Structures

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts.

C++_ MARKS 40 MIN

CS3157: Advanced Programming. Outline

Introduction to C++ Systems Programming

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to Programming

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Exceptions, Case Study-Exception handling in C++.

The Four Polymorphisms in C++ Subtype Polymorphism (Runtime Polymorphism) Polymorphism in C

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

Basics of C++ // my first program in C++ Hello World! #include <iostream> using namespace std; int main () { cout << "Hello World!

Chapter 15 - C++ As A "Better C"

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Programming in C++: Assignment Week 8

Dr. Md. Humayun Kabir CSE Department, BUET

CSCE Practice Midterm. Data Types

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Introduction to RTTI. Jonathan Hoyle Eastman Kodak 11/30/00

Polymorphism. Zimmer CSCI 330

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

CS11 Advanced C++ Fall Lecture 7

C++ Inheritance. Dr. Md. Humayun Kabir CSE Department, BUET

UNIT - IV INHERITANCE AND FORMATTED I/O

CPSC 427: Object-Oriented Programming

CSE 333 Lecture C++ final details, networks

C++ Namespaces, Exceptions

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Chapter 2: Basic Elements of C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2. Procedural Programming

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

CMSC 202 Midterm Exam 1 Fall 2015

EEE145 Computer Programming

Fast Introduction to Object Oriented Programming and C++

Short Notes of CS201

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Incompatibilities / Differences between C and C++

CS201 - Introduction to Programming Glossary By

C++ Programming: From Problem Analysis to Program Design, Third Edition

Basic Types, Variables, Literals, Constants

The University of Nottingham

C++ Crash Kurs. Exceptions. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

C++ Exception Handling 1

C++ Coding Standards and Practices. Tim Beaudet March 23rd 2015

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

G52CPP C++ Programming Lecture 16

EP241 Computer Programming

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Crash Course into. Prof. Dr. Renato Pajarola

IS 0020 Program Design and Software Tools

CS2141 Software Development using C/C++ C++ Basics

CPSC 427: Object-Oriented Programming

C++ Inheritance II, Casting

C++#Overview#(1)# Topics# COS320# Heejin#Ahn#

CPSC 427: Object-Oriented Programming

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE Practice Midterm. Data Types

IBM i Version 7.2. Programming IBM Rational Development Studio for i ILE C/C++ Language Reference IBM SC

1c) (iv) and (v) OR (v) only (hindsight showed that the question was more ambiguous than intended)

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Introduction Of Classes ( OOPS )

Introduction to Programming Using Java (98-388)

Homework 4. Any questions?

Compiler Construction. Lecture 10

Fundamentals of Programming. Lecture 19 Hamed Rasifard

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

Linked List using a Sentinel

Module Operator Overloading and Type Conversion. Table of Contents

Ch. 3: The C in C++ - Continued -

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

Contents. C++ As a Better C. Comments. User-defined Type Names

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

CSc Introduc/on to Compu/ng. Lecture 17 Edgardo Molina Fall 2011 City College of New York

C++ As a Better C. C++ Object Oriented Programming Pei-yih Ting NTOU CS

Pointers and Arrays. Introduction To Pointers. Using The "Address Of" The Operator & Operator. Using The Dereference. The Operator * Operator

Transcription:

C++ Type Casting Dr. Md. Humayun Kabir CSE Department, BUET

C++ Type Casting Converting a value of a given type into another type is known as type-casting. ti Conversion can be implicit or explicit 2

C++ Implicit Conversion Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. 3

C++ Implicit Conversion 4 #include <iostream> using namespace std; class A { int x; public: A(int x) {this->x=x;} x;} int getx() {return x;} }; class B{ int x, y; public: B(A a) {x=a.getx(); y=a.getx();} void getxy(int &x, int &y){x=this->x; ;y=this->y;} y;} };

C++ Implicit Conversion int main(){ int x, y; A a(10); B b=a; b.getxy(x,y); cout<<"x: "<<x<<" y: "<<y<<endl; return 0; } 5

C++ Explicit Conversion Conversions that imply a different interpretation of the value, require an explicit conversion using type cast operator. Bb b=(b) a; or Bb b=b B( (a); Using type cast operators indiscriminately on classes and pointers to classes can lead to code that while being syntactically correct can cause runtime errors. 6

C++ Explicit Conversion #include <iostream> using namespace std; class CDummy { float i,j; }; class CAddition { int x,y; public: CAddition (intt a, int b) { x=a; y=b; } int result() { return x+y;} }; 7

C++ Explicit Conversion int main () { CDummy d; CAddition * padd; padd = (CAddition*) &d; cout << padd->result(); return 0; } 8

C++ Explicit Conversion Traditional explicit type-casting allows to convert any pointer into any other pointer type, independently of the types they point to. The subsequent call to member function will produce either a run-time error or a unexpected result. In order to control these types of conversions between classes, there are four specific casting operators: dynamic_cast, reinterpret_cast, static_cast and const_cast. 9

C++ dynamic_cast dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class. dynamic_castcast is always successful when we cast a class to one of its base classes 10

C++ dynamic_cast class CBase { }; class CDerived: public CBase { }; CBase b; CBase* pb; CDerived d; CDerived* pd; pb = dynamic_cast<cbase*>(&d); * // ok: derived-to-base pd = dynamic_cast<cderived*>(&b); // wrong: base-to-derived 11

C++ dynamic_cast #include <iostream> #include <exception> using namespace std; class CBase { virtual void dummy() {} }; class CDerived: public CBase { int a; }; int main () { try { CBase * pba = new CDerived; CBase * pbb = new CBase; CDerived * pd; pd = dynamic_cast<cderived*>(pba); if (pd==0) cout << "Null pointer on first type-cast" << endl; pd = dynamic_cast<cderived*>(pbb); if (pd==0) cout << "Null pointer on second type-cast" << endl; } catch (exception& e) {cout << "Exception: " << e.what();} return 0; } 12

C++ dynamic_cast When dynamic_cast cannot cast a pointer because it is not a complete object of the required class, it returns a null pointer to indicate the failure. If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_cast is thrown. dynamic_cast can also cast null pointers even between pointers to unrelated classes. can also cast pointers of any type to void pointers (void*). 13

C++ static_cast static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. ensures that at least the classes are compatible if the proper object is converted but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. could lead to runtime errors 14

C++ static_cast class CBase {}; class CDerived: public CBase {}; CBase * a = new CBase; CDerived * b = static_cast<cderived*>(a); //OK 15

C++ static_cast static_cast can also be used to perform any other non-pointer conversion that t could also be performed implicitly Or any conversion between classes with explicit constructors or operator functions 16

C++ reinterpret_cast reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. class A {}; class B {}; A* a = new A; B * b = reinterpret_cast<b*>(a); 17

C++ const_cast const_cast manipulates the constness of an object, either to be set or to be removed. #include <iostream> using namespace std; 18 void print (char * str) { cout << str << endl; } int main () { const char * c = "sample text"; print ( const_cast<char *> (c) ); return 0; }

C++ typeid typeid allows to check the type of an expression returns a reference to a constant t object of type type_info that is defined in the standard header file <typeinfo> This returned value can be compared with another one using operators == and!= can serve to obtain a null-terminated character sequence representing the data type or class name by using its name() member 19

C++ typeid #include <iostream> #include <typeinfo> using namespace std; int main () { int * a, b; a=0; b=0; if (typeid(a)!= typeid(b)) { cout << "a and b are of different types:\n"; cout << "a is: " << typeid(a).name() << '\n'; cout t<<"bi is: "<<t typeid(b).name() () << '\n';' } return 0; } 20

C++ typeid 21 #include <iostream> #include <typeinfo> #include <exception> using namespace std; class CBase { virtual void f(){} }; class CDerived : public CBase {}; int main () { try { CBase* a = new CBase; CBase* b = new CDerived; cout << "a is: " << typeid(a).name() << '\n'; cout << "b is: " << typeid(b).name() << '\n'; cout << "*a is: " << typeid(*a).name() ( ) () << '\n'; cout << "*b is: " << typeid(*b).name() << '\n'; } catch (exception& e) { cout << "Exception: " << e.what() << endl; } return 0; }

C++ conversion function A conversion function that belongs to a class X specifies a conversion from the class type X to the type specified by the conversion_type. class Y { int b; public: operator int(){return b;} }; void f(y obj) { } int i = int(obj); int j = (int)obj; int k = i + obj; 22

C++ conversion function restrictions 23 Classes, enumerations, typedef names, function types, or array types cannot be declared or defined in the conversion_type. You cannot use a conversion function to convert an object of type A to type A, to a base class of A, or to void. Conversion functions have no arguments, and the return type is implicitly the conversion type. Conversion functions can be inherited. You can have virtual conversion functions but not static ones.

cout<< Thank You <<endl; cout<< Have a Good Day <<endl; 24