Docsity

C++ Programming: Topics Covered in CMSC 433 at University of Maryland, Fall 2001 - Prof. A, Study notes of Programming Languages

Toggle sidebar
bg1
CMSC 433, Adam Porter, Univ. of Maryland
1
CMSC433, Fall 2001
Programming Language
Technology and Paradigms
Adam Porter
Sept. 4, 2001
CMSC 433, Fall 2001 - Adam Porter 3
C++ without Classes
•Don’t need to say “struct”
•New libraries
•function overloading
–confusing link messages
•default parameters
•void *
–C++ requires explicit conversion from void *
CMSC 433, Fall 2001 - Adam Porter 4
More C++ without Classes
•Dynamic initialization of globals
–no way to control order between files
•References
–Compiler treats as pointers
–Programmer doesn’t
–Once initialized to reference an address, cannot
be made to reference a different address
–Used for pass-by-reference parameters
CMSC 433, Fall 2001 - Adam Porter 7
Project 1
•Project 1 - C++ - due Wed, Sep. 19th
•C++ Linked List and Expanding Int Array
–don’t use other C++ libraries
–Expanding Int array should used shared
representation, copy on write
•so that copying is fast
•Info on web page under Projects link
CMSC 433, Fall 2001 - Adam Porter 18
References
int x,y;
int *p = &x;
int &q = y;
q++; // increments y
(*p)++; // increments x
q = x; // assigns value of x to y
p=&y; // makes p point to y;
CMSC 433, Fall 2001 - Adam Porter 19
new/delete
•use new A to allocate one A
•use new A[size] to allocate an array of size
A’s
•use delete to free one A
•use delete[] to free an array of A
•new/delete invoke constructors/destructors
–for all elements of an array
–delete[] must be given pointer to first element
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download C++ Programming: Topics Covered in CMSC 433 at University of Maryland, Fall 2001 - Prof. A and more Study notes Programming Languages in PDF only on Docsity!

CMSC433, Fall 2001

Programming Language

Technology and Paradigms

Adam Porter

Sept. 4, 2001

CMSC 433, Fall 2001 - Adam Porter 3

C++ without Classes

  • Don’t need to say “struct”
  • New libraries
  • function overloading
    • confusing link messages
  • default parameters
  • **void ***
    • C++ requires explicit conversion from **void ***

CMSC 433, Fall 2001 - Adam Porter 4

More C++ without Classes

  • Dynamic initialization of globals
    • no way to control order between files
  • References
    • Compiler treats as pointers
    • Programmer doesn’t
    • Once initialized to reference an address, cannot be made to reference a different address
    • Used for pass-by-reference parameters

CMSC 433, Fall 2001 - Adam Porter 7

Project 1

  • Project 1 - C++ - due Wed, Sep. 19th
  • C++ Linked List and Expanding Int Array
    • don’t use other C++ libraries
    • Expanding Int array should used shared representation, copy on write - so that copying is fast
  • Info on web page under Projects link

CMSC 433, Fall 2001 - Adam Porter 18

References

int x,y;

int *p = &x;

int &q = y;

q++; // increments y

(*p)++; // increments x

q = x; // assigns value of x to y

p=&y; // makes p point to y;

CMSC 433, Fall 2001 - Adam Porter 19

new/delete

  • use new A to allocate one A
  • use new A[size] to allocate an array of size

A’s

  • use delete to free one A
  • use delete[] to free an array of A
  • new/delete invoke constructors/destructors
    • for all elements of an array
    • delete [] must be given pointer to first element

CMSC 433, Fall 2001 - Adam Porter 20

Data Abstraction

  • Avoid name clashes
  • Hide implementation
  • Override “standard” functionality

CMSC 433, Fall 2001 - Adam Porter 21

IntArray example

  • Without OO:

void IA_init(IntArray *ia); void IA_cleanup(IntArray * ia); void IA_setSize(IntArray * ia, int value); int IA_getSize(IntArray * ia); void IA_setElem(IntArray * ia, int index, int value); int IA_getElem(IntArray * ia, int index);

  • With OO: class IntArray{ public: IntArray(); ~IntArray(); void setSize(int value); int getSize(); void setElem(int index, int value); int getElem(int index); private: …}

CMSC 433, Fall 2001 - Adam Porter 22

Access control

  • A member can be public/protected/private
  • Once declared, access specification remains

in effect until changed (e.g., for following

members

  • For classes, default access is private
    • For structs, default access is public
    • no other differences between classes and structs

CMSC 433, Fall 2001 - Adam Porter 23

Access levels

  • public – any function/method allowed

access

  • private - only methods in the class allowed

access

  • protected - like private, except that

subclasses (derived classes) can access

inherited members

CMSC 433, Fall 2001 - Adam Porter 24

Protected access

  • Class A { private: int x; protected: int y; }
  • Class B : public A { static int foo(A a, B b) { int i = a.x; // illegal int j = a.y; // illegal int k = b.x; // illegal int n = b.y; // LEGAL …}

CMSC 433, Fall 2001 - Adam Porter 25

Friends

  • A class X can declare a class Y or a

function f as a friend

  • Gives Y or f access to all of X’s private and protected data
  • Friendship is not transitive
  • If X declares Y as a friend, and Y declares Z as a friend, Z can’t see X’s private data
  • It’s not inherited either
  • a class derived from Y cannot access X’s private or protected data

CMSC 433, Fall 2001 - Adam Porter 35

operator =

IntArray& operator=(const IntArray &a) { if (this == &a) return this; if (size != a.size) { delete [] rep; rep = new int[a.size]; size = a.size;} memcpy(rep, a.rep, sizeof(int)size); return *this; }

} CMSC 433, Fall 2001 - Adam Porter 36

One arg constructors

  • A one argument constructor is also used for

type conversion

  • A(int sz) allows an int to be used anywhere an A is expected
  • only one level of conversion is supported
    • if a B is required and an int is supplied, the system won’t convert an int to an A, which is then converted to a B
  • Can mark constructor as explicit to avoid this feature

CMSC 433, Fall 2001 - Adam Porter 37

Subtyping – Derived classes

  • if class D has class B as a public base type
    • a pointer to a D can be provided anywhere a pointer to a B is expected
    • a reference to a D can be provided anywhere a reference to a B is expected
  • class D should fulfill B’s public contract
    • something that expects a pointer to a Band is given a pointer to a D shouldn’t be surprised

CMSC 433, Fall 2001 - Adam Porter 38

Virtual functions

  • Without virtual functions, B’s functionality

will be invoked on objects pointed to by a B

pointer

  • determined from explicit type of pointer
  • With virtual functions
  • dispatching based on run-time type of object pointed to
  • compile-time type of arguments must match argument types exactly to override in derived class

CMSC 433, Fall 2001 - Adam Porter 39

Non-virtual functions

  • Non-virtual functions have confusing semantics
    • function you get depends on type of pointer used to reference the object
  • But virtual functions may be more expensive to invoke
  • Should probably make functions non-virtual only if never overridden - final in Java

CMSC 433, Fall 2001 - Adam Porter 40

Common Subytping Errors

  • An array of D’s can be given to someone
    • who expects an array of B’s
  • B’s public contract may involve assigning

another B to it

  • What is the right thing to do
    • when a D is assigned a B?
    • when a B is assigned a D?

CMSC 433, Fall 2001 - Adam Porter 41

Operator= and subtyping

  • struct B { B& virtual operator=(const B & b) {…} };
  • struct D : public B { D & virtual operator=(const D & d) {…}};
  • B b; D d; B* pbb = &b; B* pbd = &d;
    • b = d;
    • d = b;
    • *pbb = *pbd;
    • *pbd = *pbb;

// B::operator=(const B&) // Illegal (why?) // B::operator=(const B&) // B::operator=(const B&)

CMSC 433, Fall 2001 - Adam Porter 42

Virtual operator=

  • virtual declaration didn’t matter; arguments

not identical

  • struct B { B& virtual operator=(const B & b) {…} };
  • struct D : public B { D & virtual operator=(const B & b) {…}}; D & virtual operator=(const D & d) {…}};

CMSC 433, Fall 2001 - Adam Porter 43

Similar problems elsewhere

  • Copy constructor
    • overriding not an issue
    • watch out for omitting & for a reference parameter
  • operator==
    • almost identical set of problems to operator=

CMSC 433, Fall 2001 - Adam Porter 44

Covariance of return types

  • When you override a function, your return

type can be a subtype of the method you are

overriding

  • struct B { virtual B* getChild(); }
  • struct D : public B { virtual D * getChild(); }

CMSC 433, Fall 2001 - Adam Porter 45

Covariance

  • Covariance of return types is OK
    • Somebody who expects a B, is given a D
    • invokes getChild() on it
    • Expects a B, is given a D
    • No surprise…
  • Not OK for argument types

CMSC 433, Fall 2001 - Adam Porter 46

Argument types can’t be

covariant

  • Consider if D::f overrode B::f in
    • struct B {virtual void f(B* p);}
    • struct D : public B {virtual void f(D* p);}
  • Somebody who expects a B, is given a D
    • invokes f(new B()) on it
    • D::f would be surprised!
      • expected a D, got a B

CMSC 433, Fall 2001 - Adam Porter 56

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 - Adam Porter 57

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*

CMSC 433, Fall 2001 - Adam Porter 58

dynamic_cast

  • Looks at object to determine:
    • if legal (returns null otherwise)
    • 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 - Adam Porter 59

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 - Adam Porter 60

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 - Adam Porter 61

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 - Adam Porter 62

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 - Adam Porter 63

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

CMSC 433, Fall 2001 - Adam Porter 64

What happened?

  • Constructor B() chains to constructor for

A()

  • while doing constructor for A(), object is an A
  • Then, perform void constructor for B
  • now, object is a B

CMSC 433, Fall 2001 - Adam Porter 65

Namespaces

  • What if I’ve defined a List class
  • And you’ve written a different List class
  • Can my code and your code be used in the

same program?

  • No - Can’t have two different classes named the same
  • Namespaces to the rescue
  • Similar to packages in Java

CMSC 433, Fall 2001 - Adam Porter 66

Using namespaces

  • namespace Foo {

class List { … };

  • namespace Bar {

class List { … };

  • Foo::List queue = new Foo::List();

CMSC 433, Fall 2001 - Adam Porter 67

namespace Foo { … };

  • All new definitions are in namespace Foo
  • Make all definitions previously declared in

Foo available

  • OK to open and close a namespace:

namespace A { … };

namespace B { … };

namespace A { … };

CMSC 433, Fall 2001 - Adam Porter 74

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 - Adam Porter 75

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

CMSC 433, Fall 2001 - Adam Porter 76

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 - Adam Porter 77

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 - Adam Porter 78

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 - Adam Porter 79

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 - Adam Porter 80

Example - File closer

  • class FileCloser {

const FILE *f;

public:

FileCloser(FILE *f) { this.f = f; };

virtual ~FileCloser() { f.close(); }

CMSC 433, Fall 2001 - Adam Porter 81

Example - Monitor lock

  • class MonitorLock {

Monitor & m;

public:

MonitorLock(Monitor & mon) : m(mon)

{ m.lock(); }

virtual ~MonitorLock()

{ m.unlock(); }