Casts in C++, Casting Between Classes, Static Cast - Lecture Notes | CMSC 433, Study notes of Programming Languages

Material Type: Notes; Professor: Sussman; Class: PROG LANG TECH & PDGMS; Subject: Computer Science; University: University of Maryland; Term: Unknown 1989;

Typology: Study notes

Pre 2010

Uploaded on 02/13/2009

koofers-user-rw1
koofers-user-rw1 🇺🇸

4.5

(2)

10 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CMSC 433, Alan Sussman, University of
Maryland
1
CMSC433, Fall 2001
Programming Language
Technology and Paradigms
More C++
Alan Sussman
September 13, 2001
CMSC 433, Fall 2001 -Alan Sussman 2
Administrivia
Extra office hour today 4-5PM
Project 1
public drivers posted
a gzipped tar file with driver codes and
corresponding outputs
4 list driver files, 2 array driver files
questions?
CMSC 433, Fall 2001 -Alan Sussman 3
Last time
One arg constructor for type conversion
Derived classes and subtypes
in C++ generally means virtual classes
derived class should obey public contract of base class
overriding only based on declared types of parameters
covariance of return types allowed
but not of parameters/arguments
Object hierarchy design
has-a vs. is-a
CMSC 433, Fall 2001 -Alan Sussman 4
Casts in C++
static_cast
C style cast, with different syntax
dynamic_cast
cast from base class ptr to derived class ptr
returns null if not instance of derived class
const_cast
to remove/add const attribute from a pointer
reinterpret_cast
interpret bits
CMSC 433, Fall 2001 -Alan Sussman 5
Casting between classes
In C++ with multiple inheritance, casting between
a ptr to a base type and a ptr to a derived type
may require adding/subtracting offset
may require run-time lookups
if you have virtual base classes
Reusing the bit pattern likely to be badly wrong
So C++ provides various cast operators to provide
some safety guarantees
CMSC 433, Fall 2001 -Alan Sussman 6
static_cast
For pointers, assumes correct, doesnt look
at object
B *b = static_cast<B *>(d); // OK
D *d = static_cast<D *>(b); // ?
Also used for casting between built-in types
integers, doubles, ...
replaces C style cast
also can be used to cast from a void*
pf3
pf4
pf5

Partial preview of the text

Download Casts in C++, Casting Between Classes, Static Cast - Lecture Notes | CMSC 433 and more Study notes Programming Languages in PDF only on Docsity!

Maryland

CMSC433, Fall 2001

Programming Language

Technology and Paradigms

More C++

Alan Sussman September 13, 2001

CMSC 433, Fall 2001 - Alan Sussman 2

Administrivia

  • Extra office hour today – 4-5PM
  • Project 1
    • public drivers posted
      • a gzipped tar file with driver codes and corresponding outputs
      • 4 list driver files, 2 array driver files
    • questions?

CMSC 433, Fall 2001 - Alan Sussman 3

Last time

  • One arg constructor – for type conversion
  • Derived classes and subtypes
    • in C++ generally means virtual classes
    • derived class should obey public contract of base class
    • overriding only based on declared types of parameters
    • covariance of return types allowed
      • but not of parameters/arguments
  • Object hierarchy design
    • has-a vs. is-a CMSC 433, Fall 2001 - Alan Sussman 4

Casts in C++

  • static_cast
    • C style cast, with different syntax
  • dynamic_cast
    • cast from base class ptr to derived class ptr
    • returns null if not instance of derived class
  • const_cast
    • to remove/add const attribute from a pointer
  • reinterpret_cast
    • interpret bits

CMSC 433, Fall 2001 - Alan Sussman 5

Casting between classes

  • In C++ with multiple inheritance, casting between a ptr to a base type and a ptr to a derived type - may require adding/subtracting offset - may require run-time lookups - if you have virtual base classes
  • Reusing the bit pattern likely to be badly wrong
  • So C++ provides various cast operators to provide some safety guarantees

CMSC 433, Fall 2001 - Alan Sussman 6

static_cast

  • For pointers, assumes correct, doesn’t look at object - B *b = static_cast<B *>(d); // OK - D *d = static_cast<D *>(b); //?
  • Also used for casting between built-in types
    • integers, doubles, ...
    • replaces C style cast
    • also can be used to cast from a void*

Maryland

CMSC 433, Fall 2001 - Alan Sussman 7

dynamic_cast

  • Looks at object to determine:
    • if legal (returns null otherwise)
    • if pointer value adjustment needed
  • Generally used for safely casting from base type to derived type
  • Requires that code be compiled with RTTI
    • Run time type information

CMSC 433, Fall 2001 - Alan Sussman 8

const_cast

  • To remove or add const or volatile declarations - sometimes necessary because const is part of a (member) function’s type signature - can be useful to invoke a non- const member function on a const object - assuming that the function behaves properly in this situation

CMSC 433, Fall 2001 - Alan Sussman 9

reinterpret_cast

  • interpret bits
  • VERY dangerous, no checks
  • No adjustments applied
  • one valid use is to cast out of void*
  • and potentially useful for explicitly placing object in memory at a fixed location with new

CMSC 433, Fall 2001 - Alan Sussman 10

Abstract classes

  • An abstract class cannot be directly instantiated
  • Although subclasses may
  • In C++, any class with an abstract function is abstract - define a method to be abstract by setting it = 0 (no implementation)

CMSC 433, Fall 2001 - Alan Sussman 11

Constructor chaining

  • For a constructor, you can give the arguments to the constructors for: - the base classes - the instance variables
  • If nothing provided, void constructor used
  • Ex. class B : public A { C c1, c2; D d1; public: B() : A(42), c1(“hello”), c2(“hi”), d1() { …. }

CMSC 433, Fall 2001 - Alan Sussman 12

What does B() print?

  • struct A { A() { g(); }; virtual void f() { cout << “A”; }; virtual void g() { f() }; }
  • class B : public A { B() { g(); }; virtual void f() { cout << “B”; }; }

Maryland

CMSC 433, Fall 2001 - Alan Sussman 19

Inheriting namespaces

  • namespace Foo { using A; using B; class List { … }; };
  • using Foo { // Foo::List and all names from A // and B available } CMSC 433, Fall 2001 - Alan Sussman 20

namespaces aren’t databases

  • You see X in namespace Foo only if the compiler sees X declared in Foo at some point earlier in the file. - doesn’t affect need to carefully link header files

CMSC 433, Fall 2001 - Alan Sussman 21

namespace aliases

  • What if two developers both write code using the namespace Parser? - back to our old problem of name clashes
  • Partial solution using namespace aliases;
  • namespace Parser = als_Parser;
  • Makes long names bearable
    • still have to come up with unique long names
    • Java style: edu_umd_cs_als_Parser? CMSC 433, Fall 2001 - Alan Sussman 22

Exceptions

  • throw exp ; -- throws an exception exp
  • try { … } catch (ExceptionType e) { … }
    • if, while executing a try block, an exception is thrown that could be passed to a function taking an ExceptionType as an argument, the catch clause is invoked with e bound to value thrown

CMSC 433, Fall 2001 - Alan Sussman 23

Exception example

struct IndexOutOfBounds{}; char String::getChar(int i) { if (i < 0 || i >= length) throw IndexOutOfBounds(); }; try { c = s.getChar(42); } catch (IndexOutOfBounds err) { cout << “Index out of bounds”; }

CMSC 433, Fall 2001 - Alan Sussman 24

Exception hierarchy

  • You can create a hierarchy of exceptions
    • Exception
      • IOException
      • BoundsException
  • Using derived classes
    • catch a reference to the base class (parameter Base&)
      • if a derived class is thrown, you catch it
    • catch value of the base class (parameter Base)
      • if derived class is thrown, copy constructor for the base class is invoked, using the obj thrown as arg

Maryland

CMSC 433, Fall 2001 - Alan Sussman 25

More exceptions

  • If you aren’t going to do anything with the exception you caught - omit variable name in catch
  • You can throw other values
    • ints, doubles
    • don’t do this …

CMSC 433, Fall 2001 - Alan Sussman 26

Exception declarations

  • You can declare the set of exceptions a function might throw - not checked at compile time
  • Checked at run-time
    • if you declare the exceptions you throw
    • and you throw something not on that list
    • function unexpected() is called
      • which by default calls terminate()
        • which by default calls abort()

CMSC 433, Fall 2001 - Alan Sussman 27

Declaring exceptions

  • Declare you might throw X or Y
    • int f(int i) throw (X,Y) { … };
  • Declare you don’t throw any exceptions
    • int g(int i) throw () { … };
  • Declare that you don’t know what exceptions you throw - int h(int i) { … };

CMSC 433, Fall 2001 - Alan Sussman 28

Using destructors

for final actions

  • Sometimes, you want to ensure you take some action when leaving a scope - no matter how you leave the scope - exception, return, fall off the bottom
  • Destructors get called no matter how you leave the scope - use them

CMSC 433, Fall 2001 - Alan Sussman 29

Example - File closer

  • class FileCloser { const FILE *f; public: FileCloser(FILE *f) { this.f = f; }; virtual ~FileCloser() { f.close(); } }

CMSC 433, Fall 2001 - Alan Sussman 30

Example - Monitor lock

  • class MonitorLock { Monitor & m; public: MonitorLock(Monitor & mon) : m(mon) { m.lock(); } virtual ~MonitorLock() { m.unlock(); } }