CS 162 Lecture Notes - Lecture 17: Virtual Function, Late Binding, Compile Time

41 views4 pages
CS 162 Lecture 17 Introduction to Polymmorphism
Polymorphism
o Inheritance prevents us from redclaring the same thing
The child can be passed in inside of the parent
o Can define function, have different definitions, at runtime the program decides
what to call depending on the type
o The ability to associate many meanings to one function name by means of a
special mechanism know as a virtual function or late binding
o Virtual functions may be used before it is defined
Define these in implementation files
o Late binding (dynamic binding): techniques of waiting until run time to
determine the implementation of a procedure
o Changing what function we are using from determining at compile time, to
determining at runtime
How to Polymorph
o Have a virtual function in the ase lass delaration, don’t hange anything else
o Class piece {
Protected:
Int r_pos;
Int c_pos;
Int color;
Char shape;
Bool captured;
Public:
Piece();
Void move(int, int);
// appropriate accessor and mutators here
virtual bool check_valid(int r, int c);
o just add virtual! That easy
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows page 1 of the document.
Unlock all 4 pages and 3 million more documents.

Already have an account? Log in

Document Summary

Cs 162 lecture 17 introduction to polymmorphism. How to polymorph: have a virtual function in the (cid:271)ase (cid:272)lass de(cid:272)laration, don"t (cid:272)hange anything else, class piece , protected: Int color: char shape, bool captured, public, piece(), void move(int, int), // appropriate accessor and mutators here, virtual bool check_valid(int r, int c); just add virtual! That easy it will change depending on what is being passed in. How does it change what occurs here: void test_bishop(bishop& p, int r, int c), bool res = p. check_valid(r,c); If the function is declared virtual in the base class, you do not need to redeclare it in the derived class. Increased storage overhead and slows the program down: a lot of memory, takes more time bc how the compiler works. If a class has one or more virtual functions, the compiler creates a virtual function table for that class: the table has a pointer for each virtual function to point to the appropriate code.

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers

Related Documents