C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is...

57
C++ and OO C++ classes and OO More Examples HW2 C++ for C Programmers by Ira Pohl

Transcript of C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is...

Page 1: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

C++ and OO

l  C++ classes and OO

l  More Examples

l  HW2

C++ for C Programmers by Ira Pohl

Page 2: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Objects

C++ for C Programmers by Ira Pohl

Page 3: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

C++ and OO

l  What happens with a declaration l  int i , j = 3; l  Declares; allocates ; initializes l  For a simple native type this happens

automatically via a stack l  Constructor – the OO function to do this

C++ for C Programmers by Ira Pohl

Page 4: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Quiz- what is printed l  int main() l  { int i = 9, j = 3; l  cout << “i is “ << i <<“ j is “ << j <<endl; l  { int i = j + 2; l  cout << “i is “ << i <<“ j is “ << j <<endl; } l  cout << “i is “ << i <<“ j is “ << j <<endl; l  }

C++ for C Programmers by Ira Pohl

Page 5: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Answer

l  i is 9 j is 3

l  i is 5 j is 3

l  i is 9 j is 3

C++ for C Programmers by Ira Pohl

Page 6: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Point and its constructor

class point{ public: point(x=0.0, y = 0.0):x(x),y(y){} //constructor double getx(){return x;} void setx(double val){x = v;} ….. private: double x, y; }; //note class_name():initializer list syntax

C++ for C Programmers by Ira Pohl

Page 7: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

This pointer --self-referential

l  Every class object has the implicit pointer l  Keyword this associate with it.

l  We will use it in the next slide

C++ for C Programmers by Ira Pohl

Page 8: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

A special method -constructor

l  point(){ x = y = 0.0;}

l  or l  point(){ this -> x = 0.0; this ->y = 0.0} l  Or best l  point():x(0.0),y(0.0){}

l  Default constructor – the constructor whose signature is void.

C++ for C Programmers by Ira Pohl

Page 9: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Use

l  point p, q, r; // all call constructor of void signature

C++ for C Programmers by Ira Pohl

Page 10: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Constructor overloading

l  It is useful to have multiple ways to initialize an object like point.

l  point(double x, double y) l  {this -> x = x; this ->y = y;}

l  this used to disambiguate

C++ for C Programmers by Ira Pohl

Page 11: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Argument and member confusion

l  point(double x, double y) l  {this -> x = x; this ->y = y;}

l  This lets ambiguity be resolved x=x; would not work l  Better use initialization syntax l  point(double x, double y):x(x),y(y){}

C++ for C Programmers by Ira Pohl

Page 12: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

More Constructors

Constructors: Initialize Constructors: Convert Constructors: Allocate Also: constructors can check for correctness

C++ for C Programmers by Ira Pohl

Page 13: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Memory management

l  new - allocator -think malloc() l  delete – deallocator – think free()

l  Both work with a heap – heap is dynamically allocated memory – unlike Java not automatically garbage collected

C++ for C Programmers by Ira Pohl

Page 14: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Simple use of new

l  char* s = new char[size];//get off heap l  int *p = new int(9); // single int initialized l  delete [] s; //delete an array l  delete p; //delete single element

l  These will get used with dynamic data structures in constructors and destructors

C++ for C Programmers by Ira Pohl

Page 15: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

~ destructor

l  Deallocator when item goes out of scope

l  Syntax within class ~classname(){ …}

l  Typical use is for calling delete to deallocate to the heap – what if you forget

l  Answer: Bad manners -memory leak

C++ for C Programmers by Ira Pohl

Page 16: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Linked List –p 168 section5.7

l  struct slistelem{ char data; slistelem* next;}

l  class slist{ //singly linked list l  public: l  slist():h(0){} //empty list l  ~slist() {release();} destructor l  …..more methods l  private: l  slistelem* h; //list head l  }

C++ for C Programmers by Ira Pohl

Page 17: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Prepend to slist

l  void slist::prepend (char* c) l  { l  slistelem* temp = new slistelem; l  assert (temp != 0); l  temp -> next = h; //single link l  temp -> data = c; l  h = temp; //update h l  }

C++ for C Programmers by Ira Pohl

Page 18: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

~ destructor

l  slist::~slist() l  { l  cout << “destructor called” << endl; l  //just for demonstration –debug l  release(); //march thru list with l  //deletes l  }

C++ for C Programmers by Ira Pohl

Page 19: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

HW2 – some ideas

l  HW2 : implement Dijkstra algorithm and use a randomly generated graph to test it.

l  A simpler problem is to compute if a graph is one connected component

l  Draw Unconnected graph

C++ for C Programmers by Ira Pohl

Page 20: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Unconnected graph

l  O

l  O O O

l  O O O

C++ for C Programmers by Ira Pohl

Page 21: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Connected graph

l  O

l  O O O

l  O O O

C++ for C Programmers by Ira Pohl

Page 22: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

First draw a randomly generated Graph

l  bool** graph; l  srand(time(0));//seed rand() l  graph = new bool*[size]; l  for(int i = 0; i <size; ++i) l  graph[i] = new bool[size]; l  //heap created 2 D array of Bool

C++ for C Programmers by Ira Pohl

Page 23: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Density is 0.19 l  for (int i = 0; i < size; ++i) l  for(int j = i; j < size; ++j) l  if (i == j) graph[i][j]= false; //no loops l  else graph[i][j] = graph[j][i] = (prob() < 0.19);

C++ for C Programmers by Ira Pohl

Page 24: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Quiz:

l  If the density is 0 the graph has no ____

l  If the density is 1 the graph is c……..

l  If the density is fixed say 0.1 then as the size of the graph gets larger it is ____likely to be connected.

C++ for C Programmers by Ira Pohl

Page 25: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Answer:

l  If the density is 0 the graph has no edges

l  If the density is 1 the graph is complete

l  If the density is fixed say 0.1 then as the size of the graph gets larger it is more likely to be connected.

C++ for C Programmers by Ira Pohl

Page 26: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

The is_connected algorithm

l  //This algorithm is a form of breadth first search - first implemented by the author in 1968 at SLAC.

l  //It was in PL1 and was a package of routines for computational graph theory.

l  //See also the Wikipedia on Breadth First Search.

l  //The algorithm is_connected uses a Boolean matrix representation of an undirected graph to determine if a graph is connected.

C++ for C Programmers by Ira Pohl

Page 27: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Details

l  It starts with node 0 and determines which nodes can be reached from this node

l  placing them in an open set and placing node 0 as the first node of a connected component.

l  Each iteration adds one node to the closed set. l  This stops with either no furter nodes reachable and

is_connected is false or all nodes being included in the closed set.

l  The algorithm was published as a SLAC report and later a generalizion was published by Hopcroft and Tarjan in 1973.

C++ for C Programmers by Ira Pohl

Page 28: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Is_connected l  bool is_connected(bool *graph[], int size) l  { l  l  int old_size =0, c_size = 0; l  bool* close = new bool[size]; l  bool* open = new bool[size]; l  for(int i = 0; i < size; ++i) l  open[i] = close[i] = false; l  open[0] = true;

C++ for C Programmers by Ira Pohl

Page 29: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

At this point

l  Open set has node 0 on it l  Question would this work if other node is

selected

l  Nothing in closed set.

l  Each iteration will add one node to closed set

C++ for C Programmers by Ira Pohl

Page 30: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Add to close l  while(c_size < size){ l  for (int i = 0; i < size; ++i){ l  old_size = c_size; l  if (open[i] && (close[i] == false)){ l  close[i] = true; c_size++;

C++ for C Programmers by Ira Pohl

Page 31: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Add to open

l  for(int j = 0; j < size; ++j) l  open[j] = open[j] || graph[i][j]; l  } l  }

C++ for C Programmers by Ira Pohl

Page 32: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Are we done? l  We are done if have all nodes in close set l  Or if no nodes available in open set

if (c_size == size) return true; if (old_size == c_size) return false;

} }

C++ for C Programmers by Ira Pohl

Page 33: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

L6 – Lists

l  List and code

C++ for C Programmers by Ira Pohl

Page 34: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

List Element l  struct list_element{

list_element(int n = 0, list_element* ptr = 0): d(n), next(ptr){} int d; list_element* next; }; Or equivalently

l  class list_element{ public:

l  list_element(int n = 0, list_element* ptr = 0): d(n), next(ptr){} int d; list_element* next; };

C++ for C Programmers by Ira Pohl

Page 35: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Quiz

l  In the previous list_element constructor, what is 0 used for?

C++ for C Programmers by Ira Pohl

Page 36: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Ans: Null Pointer

l  The zero value is the null pointer value.

l  Recall it is important in lists to test for null; they are used as sentinel values.

l  C++11 - list_element* ptr =nullptr ; l  new keyword - type safe

C++ for C Programmers by Ira Pohl

Page 37: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

List l  class list{

public: list():head(0), cursor(0){} void prepend(int n); //insert at front value n int get_element(){return cursor->d;} void advance(){ cursor= cursor-> next;} void print(); private: list_element* head; list_element* cursor; };

C++ for C Programmers by Ira Pohl

Page 38: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

prepend

l  void list::prepend(int n) { if (head == 0)//empty list case

cursor = head = new list_element(n, head); else//add to front -chain

head = new list_element(n, head); }

C++ for C Programmers by Ira Pohl

Page 39: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Quiz : prepend(5)

l  Draw how prepend (5) would work.

l  Assume a two element list -> 7 -> 3 ##

C++ for C Programmers by Ira Pohl

Page 40: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Answer

l  5 is on the front of the new list

l  Draw here----

C++ for C Programmers by Ira Pohl

Page 41: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Print() chaining l  Void list:: print(){

list_element* h = head; while(h != 0){//idiom for chaining cout << h->d << ", "; h = h -> next; } cout << "###" << endl; }

l  Should know how to use recursion l  Should know how to overload “<<“ for list

C++ for C Programmers by Ira Pohl

Page 42: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Use of list l  int main()

{ list a, b; a.prepend(9); a.prepend(8); cout << " list a " << endl; a.print(); for (int i = 0; i < 40; ++i) b.prepend(i*i); cout << " list b " << endl; b.print(); }

l  What gets printed?

C++ for C Programmers by Ira Pohl

Page 43: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Q: What gets printed

l  Follow previous code

C++ for C Programmers by Ira Pohl

Page 44: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Ans:

l  Simulate here:(run)

C++ for C Programmers by Ira Pohl

Page 45: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

More elaborate l  class list{

public: list():head(0), cursor(0){} list(const int* arr, int n); list(const list& lst);//copy constructor

l  ... ~list(); //delete private: list_element* head; list_element* cursor; };

l  Deep copy v. referential copy

C++ for C Programmers by Ira Pohl

Page 46: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Deep: Pi is transcendental

C++ for C Programmers by Ira Pohl

Page 47: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Shallow: Mom’s pie is tasty

C++ for C Programmers by Ira Pohl

Page 48: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Deep v. Shallow

l  First we will examine the copy constructor. We want to build an equivalent list that is a "deep" copy.

l  A "shallow“ copy would be a referential copy where

the new list head would be the same value as the old list head.

l  Shallow copy is a highly efficient form of copying (why?) but has a more limited utility than a deep copy(why?).

C++ for C Programmers by Ira Pohl

Page 49: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Copy constructor l 

list::list(const list& lst){ if (lst.head == 0) { head =0; cursor =0; } else …set up

l  for( cursor = lst.head; cursor != 0; ) {

…chain and create } cursor = head;

} }

C++ for C Programmers by Ira Pohl

Page 50: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

More code

l  else { cursor = lst.head; list_element* h = new list_element(); list_element* previous;

head = h; h->d = lst.head->d;

previous = h;

C++ for C Programmers by Ira Pohl

Page 51: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Chain and create l  for( cursor = lst.head; cursor != 0; )

{ h = new list_element(); h->d = cursor->d; previous->next = h; cursor = cursor->next; previous = h;

} cursor = head;

}

C++ for C Programmers by Ira Pohl

Page 52: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

~ destructor l  list::~list()

{ for( cursor = head; cursor != 0; ) {

cursor = head->next; delete head; head = cursor;

} } Here the destructor chains through the list returning each list_element created by a corresponding new.

C++ for C Programmers by Ira Pohl

Page 53: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Use this list l  int main()

{ list a, b; int data[10] = {3,4, 6, 7, -3, 5}; list d(data, 6); list e(data, 10); a.prepend(9); a.prepend(8); cout << " list a " << endl; a.print();

C++ for C Programmers by Ira Pohl

Page 54: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

l  for (int i = 0; i < 40; ++i)

b.prepend(i*i); cout << " list b " << endl; b.print(); list c(b); c.print(); d.print(); e.print(); } Make sure you know where each constructor and destructor is invoked. Also what is printed?

C++ for C Programmers by Ira Pohl

Page 55: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

Dynamic data Structures in STL

l  The standard template library has the following data structures available and you are free to use them in your problem:

l  #include <vector> l  can then use vector<type> name(size); l  vector is the most used – it is nearly

efficient as araw array and is safer and expandable.

C++ for C Programmers by Ira Pohl

Page 56: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

List is also available

l  #include <list> l  gets you doubly linked lists

C++ for C Programmers by Ira Pohl

Page 57: C++ classes and OO More Examples HW2 · Make sure you know where each constructor and destructor is invoked. Also what is printed? C++ for C Programmers by Ira Pohl . Dynamic data

C++ More

l  HW2 Questions? l  How to average in disconnected graphs – l  ignore them for averaging l  Density is for entire set of edges –does not mean node degree is

uniform; also for small graphs a low density leads to graph being disconnected.

l  Review end of chapter short questions

C++ for C Programmers by Ira Pohl