hex the game , & c++ inheritance - amazon s3 · tic-tac toe is a game of _____information ! ......

83
C++ for C Programmers by Ira Pohl Hex the game , & C++ Inheritance Hex Ideas Inheritance New in C++11

Upload: others

Post on 20-Jan-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Hex the game , & C++ Inheritance

l  Hex Ideas l  Inheritance l  New in C++11

Page 2: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Tic-Tac-Toe

l  Next move

Page 3: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Quiz

l  X’s Best move in last slide is? l  Tic-Tac Toe is a game of _____information l  With best play it is a win/draw/loss for X? l  The best first move for X is ?

Page 4: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Answers

l  O X l  X X O l  O [X] can win and blocks l  Perfect information (poker is not) l  Draw l  Middle square

Page 5: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Genralizing Tic-Tac-Toe

l  Board is larger (5 in a row) l  More dimensions (3 D) l  Board is more complex - hexagonal square

l  Leads to different connectivity

Page 6: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Inventors of Hex

l  Piet Hein 1942 l  John Nash 1947

l  (nobel prize, “A Beautiful Mind”)

Page 7: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Rules l  Rules l  Each player has an allocated color, Red and Blue or White and

Black[1] being conventional. Players take turns placing a stone of their color on a single cell within the overall playing board. The goal is to form a connected path of your stones linking the opposing sides of the board marked by your colors, before your opponent connects his or her sides in a similar fashion. The first player to complete his or her connection wins the game.

l  Since the first player to move in Hex has a distinct advantage, the pie rule is generally implemented for fairness. This rule allows the second player to choose whether to switch positions with the first player after the first player makes the first move.

Page 8: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Some facts

l  Nash proved the first player wins (without pie rule)

l  But even though known and finite – best play unknown for games size 11 or greater

l  Game played for computer championship tournament - last

Page 9: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Hex as a graph

l  Coordinates (0,0) to (10,10) 121 nodes

l  Map (0,0) into 0 and (0,1) into 1 and … (1,0) into 11 …

l  And (10,10) into 120.

Page 10: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Quiz

l  An internal square connects to ___ squares. l  The square that has least connections is ___ l  If each node is a square than degree

(number of edges) is between ___and ___

Page 11: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Answer

l  6 squares l  Corners have 2 connections l  Ergo degree is between 2 and 6.

Page 12: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

HW Basic Hex Program

l  For HW you will build a basic hex playing program- where a human can play your program. Your program should have some rules for selecting a “reasonable” move.

l  For a last HW, you will build a very smart hex player; l  Using Monte Carlo strategy

Page 13: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Quiz

l  Monte Carlo programs are probabilistic simulations

What is the standard pseudorandom function in C/C++?

What is srand() and how and why is it used?

Page 14: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Answers

l  int rand (void); //in <cstdlib> l  Returns a pseudo-random integral number in

the range between 0 and RAND_MAX. srand(time(NULL)) – seeds random number generator – so that each execution may start in a different part of the sequence

Page 15: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Basics of Inheritance

l  Inheritance is a Reuse Mechanism

l  Inheritance uses pure polymorphism(to be defined)

l  Inheritance imposes a type structure

l  OOP = Inheritance

Page 16: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

The OOP Design Methodology

1. Decide on an appropriate set of types 2. Design in their relatedness 3. Use inheritance to share code

among classes

Page 17: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

A Derived Class

l  Class derived from an existing class l class classname:(public|protected|private)opt basename { member declarations }; l  Keywords public, protected, and private used to

specify how base class members are accessible to derived class ##

Page 18: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Public inheritance = subtyping

l  90% rule – almost always use public inheritance

l  Then base class is the type of the whole hierarchy

l  Private inheritance is LIKEA relationship-not a subtype but inherits code/members turning them private

Page 19: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Point and duo

l  class duo{ l  public:

l  duo():first(0.0),second(0.0){} l  void set_first(double d){first = d;} l  void set_second(double d){second = d;} l  double get_first(){return first;} l  double get_second(){return second;}

l  protected: // intermediate data hiding –nb need for this example l  double first, second;

l  };

Page 20: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Point inherits publically

l  class point:public duo{ l  public: l  double length(){ return sqrt(first* first + second* second);} l  };

l  Public inheritance 90% rule – point is a subtype

l  All public and private members inherited –including constructor

Page 21: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Use point

l  int main() l  {

l  point q; l  q.set_first(3.0); q.set_second(4.0); l  cout << q.get_first() << ", " << q.get_second() << endl; l  cout << q.length() << endl; l  return 0;

l  }

l  “A point is a duo, but not all duo’s are points”-Socrates

Page 22: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

What did that program print?

l  point q; l  q.set_first(3.0); q.set_second(4.0); l  cout << q.get_first() << ", " <<

q.get_second() << endl; l  cout << q.length() << endl;

Page 23: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Answer

l  3,4 l  5

l  Remember pythagoras

Page 24: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!2

Traits and Inheritance

l  But Mommy, wheredid my blue eyes come from?

Page 25: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

The Inheritance Mechanism

l  Means of deriving new class from existing classes, called base classes

l  Reuses existing code eliminating tedious, error prone task of developing new code

l  Derived class developed from base by adding or altering code

l  Hierarchy of related types created that share code & interface

Page 26: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Single and Multiple Inheritance

Single inheritance occurs when single base class

Multiple inheritance occurs when more than one base class

Page 27: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Credit Cards - Single Inheritance

Same basic features Each is a little different

Page 28: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Voice Mail - Multiple Inheritance

Voice mail has features of both mail and phone

Page 29: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Taxonomic Classification

Elephant and mouse both mammals l  Descriptions succinct

Root concept "mammal" l  Warm-blooded l  Higher vertebrates l  Nourish young using milk-producing mammary glands

Page 30: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Taxonomy

l  Mammal : warm blooded, nourishes young with mammary glands, DNA spec

l  Mouse is a mammal l  Elephant is a Mammal

Page 31: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Taxonomic Classification

l  In C++ terms, classes elephant and mouse derived from base class "mammal”

l  In OOP terms, elephant ISA mammal describes relationship

l  If circus had elephants, then object circus might have members of type elephant

l  Class circus HASA elephant describes subpart relationship ##

Page 32: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Quiz

l  Zoo ___ Mammal (relationship)

l  CellPhone ___ telephone (relationship)

l  Platypus ISA mammal? (T/F)

Page 33: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Answer l  Zoo HASA Mammal (relationship)—best expressed as

a member

l  CellPhone ISA telephone (relationship)-best expressed by public inheritance

l  Platypus ISA mammal? (T/F) True The platypus (Ornithorhynchus anatinus) is a semiaquatic mammal endemic to eastern Australia, including Tasmania. Together with the four species of echidna, it is one of the five extant species of monotremes.

Page 34: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Virtual Member Functions

l  Functions declared in base class and redefined in derived class

l  Class hierarchy defined by public inheritance creates related set of user types, all of whose objects may be pointed at by a base class pointer

l  By accessing virtual function through this pointer, C++ selects appropriate function definition at run-time ##

Page 35: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Duo point point3d -use virtual

l  class point:public duo{ l  public: l  point():duo(){} //initialize base object l  point(double x, double y = 0.0):duo(x, y){} l  virtual double length(){ return sqrt(first* first + second* second);} l  }; //virtual is pure polymorphism and remains

l  class point3d:public point{ l  public: l  point3d():point(),z(0.0){} l  double length(){ return sqrt(first*first + second*second + z*z);}//virtual l  void set_z(double d){z = d;} l  private: l  double z; l  };

Page 36: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Use of virtual

l  point q, r(3.0, 4.0); l  q.set_first(3.0); q.set_second(4.0); l  cout << q.get_first() << ", " << q.get_second() << endl; //3, 4 l  cout << q.length() << endl; //5 l  point3d t; l  t.set_first(5.0); t.set_second(6.0); t.set_z(7.0); l  cout << t.length() << endl; //10.4881

l  Which length gets used can be determined at runtime l  point* ptr_p = &t; ptr_p ->length() -polymorphic

Page 37: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Pure Polymorphism

l  Object being pointed at must carry around type information so distinction can be made dynamically

l Feature typical of OOP code l  Each object "knows" how it is acted on l  Inheritance designed into software to maximize

reuse and allow natural modeling of problem domain ##

Page 38: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

C++11 Feature - final

l  What if you do not want a class to ever be a base class l  C++11 allows you to make if final l  class point3d final:public point {//no further inheritance l  public: l  point3d():point(),z(0.0){} l  double length(){ return sqrt(first*first + second*second + z*z);}//virtual l  void set_z(double d){z = d;} l  private: l  double z; l  };

l  //nota bene: final is a contextual keyword and can be an identifier

Page 39: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Topics on Inheritance

l  Subtyping and Code Reuse l  Typing Conversions and Visibility l  Abstract Base Classes l  Multiple Inheritance l  Inheritance and Design l  Detailed C++ Considerations l  New C++11 features,eg. final, default,delete …

Page 40: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Hex, and Inheritance

l  Hex Ideas – will also be our term project l  Inheritance

Page 41: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

HEX Discussion

Page 42: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

HEX first steps

l  Hex hw - get a working program that plays legal Hex ; makes legal moves, checks

opponents moves as legal, knows when game is won; Use some playing strategy – such as extend longest path or block opponents longest path or …

Page 43: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Hex ideas l  Can play or read about at many sites.

l  Bridges are one critical idea.

l  Two (groups of) stones are safely connected if nothing can stop them from being connected even if the opponent has the next move. One example of this is the bridge. Let A, B, C and D be the hexes that make up a rhombus, with A and C being the non-touching pair.

l  To form a bridge, a player places stones at A and C, leaving B and D empty. If the opponent places a stone at B or D, the remaining hex can be filled to join the original two stones into a single group. This strategy is very useful throughout the game.

Page 44: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Hex as a graph

l  Coordinates (0,0) to (10,10) 121 nodes

l  Map (0,0) into 0 and (0,1) into 1 and … (1,0) into 11 …

l  And (10,10) into 120.

Page 45: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

More on mapping

l  a % b is the integer remainder of a divide by b l  So 3 %10 is 3 and 35 % 10 is 5.

l  Node number n = i * 11 + j for square (i,j) eg (2,2) is 24, (10,10) is 120 --- have nodes labeled from 0 to 120

l  For square n i = n/11, j = n % 11 // here it is int division

l  So gives a mapping from nodes to coordinates

Page 46: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Quiz l  What node is the square (3, 5) ?

l  What square is the node 21?

Page 47: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Answer l  (3,5) is node 38

l  21 maps to 21/11 = 1 l  21%11 = 10 --- so (1,10) is coordinate

Page 48: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

One style for a hexGraph 11*11

l  class hexGraph{ l  public: l  hexGraph(){ l  int count =0; l  edgelist.resize(121); l  for(int i =0; i <11; i++) l  for(int j =0; j <11; j++) l  makeNode( i, j, edgelist[count++]); l  } l  private: l  vector< deque<int> > edgelist; l  };

Page 49: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Code for creating edge list for an internal node

l  else l  { //internal node l  elist.push_front(i*11 + j +1); l  elist.push_front(i*11 + j -1); l  elist.push_front( (i+1)*11 + j ); l  elist.push_front( (i+1)*11 + j+1 ); l  elist.push_front( (i-1)*11 + j ); l  elist.push_front( (i-1)*11 + j - 1); l  }

Page 50: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Still need special corners/edges

l  This will get you a graph representation

l  Still need to have a way to test whether the game is over l  And who won(path algorithm)

l  Need a simple strategy for the AI in the game l  -such as extending the longest current subpath or blocking the

same for the opponent.

Page 51: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Quiz

l  How would you test for a corner node on a n by n board?

Page 52: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Answer

l  if( i ==0 && j == 0) //upper left corner

l  if( i == n-1 && j == n-1) //lower right corner

Page 53: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Inheritance

Page 54: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

The Inheritance Mechanism

l  Means of deriving new class from existing classes, called base classes

l  Reuses existing code eliminating tedious, error prone task of developing new code

l  Derived class developed from base by adding or altering code

l  Hierarchy of related types created that share code & interface ##

Page 55: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

A Base Class: student

l  class student { l  public: l  enum year { fresh, soph, junior, senior, grad }; l  student(char* nm, int id, double g, year x); l  void print() const; //??? What does this mean l  protected: l  int student_id; l  double gpa; l  year y; l  char name[30]; l  };

Page 56: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Quiz

l  void print() const; //??? What does this mean

Page 57: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Answer

l  void print() const; l  Const here means the this pointer –points at an

instance that cannot be mutated (changed) l  It is used by the compiler for const correctness

Page 58: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

A Derived Class: grad_student

l  class grad_student : public student {//public - subtype l  public: l  enum support { ta, ra, fellowship, other }; l  grad_student(char* nm, int id, double g, l  year x, support t, char* d, char* th); l  void print() const; l  protected: l  support s; l  char dept[10]; l  char thesis[80]; l  };

Page 59: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Inheriting from the Base Class

l  Derived class is modification of base class that inherits public and protected members of base class

l  In grad_student, student members are inherited l  student_id gpa l  name year l  print ##

Page 60: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Add New Members in Derived Class

l  Derived class adds new members to existing class members

l  grad_student has three new data members and redefined member function l  s l  dept l  thesis l  print() ##

Page 61: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Benefits of Inheritance

l  Code is reused l  grad_student uses tested code from student

l  Reflects relationship in problem domain l  Special grouping grad student outgrowth of real world

and treatment of this group l  Polymorphic mechanisms allow client code to treat

inherited class as subtype of base class l  Simplifies code, maintains subtype distinctions ##

Page 62: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Typing Conversions and Visibility

l  Publicly derived class is subtype of base l  Variable of derived class treated as if it were base

class type l  Pointer type pointer-to-base-class can point to

objects of derived class type l  Subtle implicit conversions occur between base and

derived type l  Difficult to follow what member is accessed if base and

derived class overloaded same member name ##

Page 63: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Students and Graduate Students

In many respects, they are the same, but in some they differ.

Page 64: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

More on the student Program (1 of 7)

l  student::student(char* nm, int id, double g, year x)

l  :student_id(id), gpa(g), y(x) { strcpy(name, nm); } l  Constructor for base class does series of simple

initializations l  Calls strcpy() to copy student's name ##

Page 65: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

More on the student Program (2 of 7)

l  //publicly derived l  grad_student::grad_student(char* nm, int id,

double g, year x, support t, l  char* d, char* th) l  :student(nm, id, g, x), s(t) l  { strcpy(dept, d); strcpy(thesis, th); } l  l  Constructor for student invoked as part of initializer list

l  Logically base class object needs to be constructed first before object can be completed

l  student_id and gpa are protected which makes them visible only to the derived class

Page 66: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

More on the student Program (3 of 7)

l  Reference to derived class may be implicitly converted to a reference to public base class

l  grad_student gs("Morris Pohl", 200, 3.2564, l  grad, ta, "Pharmacy", "Retail Pharmacies"); l  student& rs = gs; //alias l  student* ps = &gs; //pointer init

l  Variable rs is reference to student l  Base class of grad_student is student Reference conversion is

appropriate

Page 67: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

More on the student Program (4 of 7)

l  void student::print() l  { l  cout << name << " , " << student_id l  << " , " << y << " , " << gpa << endl; l  } l  void grad_student::print() //overridden method l  { l  student::print(); //base class info l  cout << dept << " , " << s << endl

<< thesis << endl; l  }

Page 68: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Quiz

l  void grad_student::print() //overridden method l  { l  print(); //this is changed l  cout << dept << " , " << s << endl

<< thesis << endl; l  } l  Does this compile? l  What goes wrong?

Page 69: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Answer

l  It compiles

l  It creates a recursive routine – and does not terminate

Page 70: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

More on the student Program (5 of 7)

l  #include "student.h" l  main() //Test pointer conversion rules l  { l  student s("Mae Pohl", 100, 3.425, fresh), *ps = &s; l  grad_student gs("Morris Pohl",200, 3.2564, l  grad, ta, "Pharmacy", "Retail Pharmacies"), *pgs; l  ps —> print(); //student::print l  ps = pgs = &gs; l  ps —> print(); //student::print l  pgs —> print(); //grad_student::print l  }

Page 71: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

More on the student Program (6 of 7)

l  main() declares both class variables and pointers to them

l  Conversion rule - pointer to publicly derived class may be converted implicitly to pointer to its base class

l  Pointer ps can point to objects of both classes, but pointer pgs can point only at objects of type grad_student ##

Page 72: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

More on the student Program (7 of 7)

l  First ps -> print() invokes student::print l  ps = pgs = &gs; both pointers pointing at object of type

grad_student and assignment to ps involves implicit conversion l  Second ps -> print(); invokes student::print

l  Irrelevant that pointer points at grad_student variable gs ##

l  pgs -> print(); invokes grad_student::print l  pgs is of type pointer to grad_student and, when invoked with an

object of this type, selects a member function from this class

Page 73: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Determining Access Privilege

l  Tradeoff in code reuse and efficiency l  Inheritance requires thinking about three access

boundaries l  What is to be strictly private and what is to be

protected depends on what is reusable ##

Page 74: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Virtual Function Selection

l  Typically base has virtual function and derived have their versions of function

l  Pointer to base class can point at either base or derived class objects

l  Member function selected depends on class of object being pointed at, not on pointer type

l  In absence of derived type member, base class virtual function used by default ##

Page 75: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Virtual & Overloaded Function Selection

l  Overloaded member function is compile-time selected based on signature

l  It can have distinct return types l  Once declared virtual, this property is carried

along to all redefinitions in derived classes l  virtual modifier not needed in derived functions ##

Page 76: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Virtual Function Selection (1 of 2)

l  #include <iostream.h>

l  class B { l  public: l  int i; l  virtual void print_i() const { cout << i << " inside B" << endl; } l  };

l  class D: public B { l  public: l  void print_i() const{ cout << i << " inside D" << endl; } //virtual l  };

Page 77: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

l  int main() l  { l  B b; l  B* pb = &b; //point at a B object l  D f;

l  f.i = 1 + (b.i = 1); l  pb —> print_i(); //call B::print_i() l  pb = &f; //point at a D object l  pb —> print_i(); //call D::print_i() l  }

l 

Virtual Function Selection (2 of 2)

Page 78: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Quiz

l  What gets printed?

Page 79: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Answer

1 inside B 2 inside D

Page 80: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Comments on the virt Program

l  Different print_i() executed

l  Dynamically selected on object pointed at l  "Object sent message print_i and selects its

corresponding version of method"

l  Pointer's base type is not determining method (function) selection

l  Different class objects processed by different functions at run-time

l  ADTs, inheritance, and process of objects dynamically are essentials of OOP ##

Page 81: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Confusion with Overloading

l  Member function overloading and virtual functions cause mix-ups and confusion because overriding and overloading both are in play

l  class B { l  public: l  virtual foo(int); l  virtual foo(double); l  . . . l  }; l  class D: public B { l  public: l  foo(int); l  . . . l  };

Page 82: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Confusion with Overloading (2 of 2)

l  int main() l  { l  D d; l  B b, *pb = &d; l  b.foo(9.5); //selects B::foo(double); l  d.foo(9.5); //selects D::foo(int); l  pb —> foo(9.5); //B::foo(double); l  }

l  Base class function B::foo(int) overriden in derived class

l  Base class function B::foo(double) hidden in derived class

Page 83: Hex the game , & C++ Inheritance - Amazon S3 · Tic-Tac Toe is a game of _____information ! ... OOP = Inheritance . C++ for C Programmers by Ira Pohl! The OOP Design Methodology 1

C++ for C Programmers by Ira Pohl!

Restrictions on virtual functions

l  Only non-static member functions virtual

l  Virtual characteristic is inherited

l  Derived class function automatically virtual virtual keyword not needed

l  Constructors cannot be virtual l  Destructors can be virtual ##