Discussion slides for wThe Universityyweek of October 1, 2007y of Michiganyg1Agendaz Inheritance / PolymorphismzAccess: public private prozAccess: public, private, proz Circular dependencies and z Tree, Binary Trees, Binary S:m reviewotected friendsotected, friendsforward declarationshSearch Trees2Inheritance andInheritance andzAllow us to specifyrelazAllow us to specify rela− Abstraction, generalizatTh “i ” l i hi−The “is a” relationship− Examples?zWhy is this useful in prozWhy is this useful in pro− Allows for code reuseM i t iti / i−More intuitive/expressivd Polymorphismd Polymorphismationships between typesationships between typestion, specificationogramming?ogramming?dve codeCode RCode RG l f ti litzGeneral functionality caapplied to *any* derivedz Derived classes can haspecialization by addingspecialization by addingimplementing virtual funReuseReusebitt dan be written once and d classave selective g members org members or nctionsInterfaces and IInterfaces and ITh t thi thzThere are two things th− A particular interface − A particular implementaImplementationImplementationht b ih itdhat can be inherited:ationInterfaces and IInterfaces and ITh t thi thzThere are two things th− A particular interface − A particular implementaz The virtual keyword minherited but not (neceinherited, but not (neceimplementationImplementationImplementationht b ih itdhat can be inherited:ationeans that the interface is essarily) theessarily) thePure Virtual aPure Virtual aAddi0kfzAdding =0makes a fun− No implementation is gi− Must be implemented bzAny class with at least abstractand cannot babstract, and cannot bOft d t d fizOften used to define puwith no functionalityand Abstractand Abstracttiit lnction pure virtualivenby (concrete) derived classes1 pure virtual member is be instantiatedbe instantiated“i t f ” lure “interface” classesExample: VirtuaExample: Virtuaclass Base {cla{public: void print() {puvoid print() {cout << “Base”;}}}}}lvs NonVirtuall vs. Non-Virtualass Derived: public Base {p{ublic:void print() {void print() {cout << “Derived”;}What is thWhat is thDerivBase *pDid*Derived *ppB->pDpD->phe output?he output?ved d;B = &d;*D &d*pD = &d;print();i()print();Virtual vs NVirtual vs NVirtual functions are intzVirtual functions are int− All derived types will hafunction can be called ofunction can be called o− Implementations are on“P re” irt al f nctions a−“Pure” virtual functions az Non-virtual functions sh*mandatory* implemenlclasses− Don’t override these, orNonvirtualNon-virtualterfacesterfacesave the functionality, so the on any instance of the baseon any instance of the basenly “suggestions”are onl interfacesare only interfaceshould be considered tations for derived r you get unintuitive behaviorBaseBase class TodoList {public:public:virtual int isempty() { return(1); }virtual void add(T elt) { cerr << "virtual void add(T elt) { cerr << "virtual T next() { cerr << "TodoLiit li tt (){ <<"T d Lvirtual int type() { cerr << "TodoL};ClassClass;"TodoList::add: not defined\n"; };"TodoList::add: not defined\n"; };ist::next: not defined\n"; };Li t t t d fi d\"}List::type: not defined\n"; };DerivedDerived class TodoQueue : public TodoLiclass TodoQueue : public TodoLiprivate:int mytype;int mytype;Queue q;public:public:TodoQueue(): mytype(TODOQ)it li ti t (){ t (! ivirtual int isempty() { return(!q.sivirtual void add(T elt) { q.enqueui t l T t() { if ( i ()) { tvirtual T next() { if (q.size()) { retvirtual int type() { return (mytype}};ClassesClassesist<T> {ist<T> {) {}; i())}ize()); };ue(elt); };t ( d ()) } t (0) }turn(q.dequeue()); } return (0); };e); }When Inheritance/PDo you have types/classeszDo you have types/classesz Are you tempted to implemfunctionality in several placfunctionality in several placz Can you define a natural hrelationships?relationships?Using templates vs virtualzUsing templates vs. virtualz Does the type T change th− If no, use a template− If yes, use virtual functionsto use Polymorphisms that share functionality?s that share functionality?ment identical/similar ces?ces?hierarchy using “isa” l functionsl functionshe behavior of the class?Multiple InMultiple InUildtzUse sparingly and cautz The “deadly diamond”:yclassint f()f()class Bc assf() class???nheritancenheritanceti ltiouslys Ai;class Cclass Cf() s DMultiple InMultiple InUi “it l”ih itzUsing “virtual” inheritanz Ensures that a single ingis inheritedclass B: public virtual A {…class C: public virtual A {…class D: public A, public B p,pnheritancenheritancelbiitnce resolves ambiguitynstance of the base class …};…};{…};{};AccessAccess Pi tzPrivate− Access only within the cz PublicAccess from anywhere−Access from anywherez Protected− Access within this classWhy do we makeControlControlclasss and any derived classes anything private?Friends FunctioFriends FunctioAll t i tzAllows access to privatby-case basisclass myClass {class myClass {int myPrivateVar;friend void myFriendfriend class myFrienfriend class myFrien};ns and Classesns and Classesbe members on a case-dFunction();dClass;dClass;Classes aClasses aWh t th diffzWhat are the differencestructs in c++?nd Structsnd Structsbt l des between classes andClasses aClasses aWh t th diffzWhat are the differencestructs in c++?− Classes default to priva− Structs default to publicz What about default typend Structsnd Structsbt l des between classes and ate accessc access`e of inheritance?Private ConstrucPrivate ConstrucChitzCan you have private cdestructors?ctors/Destructorsctors/Destructorstt dconstructors andPrivate ConstrucPrivate ConstrucChitzCan you have private cdestructors?− Yes, but why?z Gives you very explicit creation/deletioncreation/deletion− Use friends to declare e“Silt”di tt−“Singleton” design patte− Reference counted objectors/Destructorsctors/Destructorstt dconstructors and control over explicit ownershipernectsPublic vs PrivaPublic vs. PrivaPublic inheritancezPublic inheritance− public members stay pu− “is a” relationship− Class Derived: public BzPrivate inheritancePrivate inheritance − public members becom“implemented as a”−implemented as a− Class Derived: private Bate Inheritanceate Inheritanceublic in the derived classBase {…};e private in the derived classBase {…};Circular DeCircular DeHd l izHow do you resolve cir− First, try to redesign witclass A {publicpublicB* myB;void f(B* b)f(
View Full Document