chapter 11 inheritance and polymorphism §11.1 concept of inheritance §11.2 accessibility in...

Click here to load reader

Upload: silvia-hawkins

Post on 17-Jan-2016

253 views

Category:

Documents


1 download

TRANSCRIPT

  • Chapter 11Inheritance and Polymorphism11.1 Concept of Inheritance11.2 Accessibility in Inheritance11.3 Constructor/Destructor in Inheritance11.4 Multiple Inheritance11.5 Redefining Functions 11.6 Virtual Function and Polymorphism11.7 Abstract Classes11.8 Dynamic Casting

  • *11.1 Concept of Inheritance ()The is a relationshipApple is a fruitElephant is an animalCircle is a shape A is a B A has the characteristics/features/properties of B A inherits B Class A inherits class BInheritance can extend existing classes!

  • *Class InheritanceSyntax: BA Base Parent Super-Class Derived-Class Childclass DerivedClass : acckeyword BaseClass{};class A: public B{public:private:};BA

  • *Example of InheritanceGeometricObject.hGeometricObject.cppDerivedCircle.hDerivedCircle.cppRectangle.hRectangle.cppTestGeometricObjectRun

    The color of the object (default: white).

    Indicates whether the object is filled with a color (default: false).

    Creates a GeometricObject.

    Creates a GeometricObject with the specified color and filled values.

    Returns the color.

    Sets a new color.

    Returns the filled property.

    Sets a new filled property.

    Returns a string representation of this object.

    Rectangle

    -width: double

    -height: double

    +Rectangle()

    +Rectangle(width: double, height: double)

    +Rectangle(width: double, height: double, color: string, filled: bool)

    +getWidth(): double

    +setWidth(width: double): void

    +getHeight(): double

    +setHeight(height: double): void

    +getArea(): double

    +getPerimeter(): double

    GeometricObject

    -color: string

    -filled: bool

    +GeometricObject()

    +GeometricObject(color: string, filled: bool)

    +getColor(): string

    +setColor(color: string): void

    +isFilled(): bool

    +setFilled(filled: bool): void

    +toString(): string

    Circle

    -radius: double

    +Circle()

    +Circle(radius: double)

    +Circle(radius: double, color: string, filled: bool)

    +getRadius(): double

    +setRadius(radius: double): void

    +getArea(): double

    +getPerimeter(): double

    +getDiameter(): double

  • *A Tip about Generic Programming()With inheritance, an object of a derived class can be used wherever an object of the base class is requiredThis is a kind of GP

    GP permits writing common functions or types that differ only in the types operated onTemplate () (in Chapter 15) is the main GP technique in C++void showArea(GeometricObject gb){}; Circle cl; Rectangle rt;showArea( cl); showArea(rt);

  • *11.2 Accessibility in InheritanceThe protected KeywordA protected data field or function can be accessed by name in its derived classesclass B {public: int i;protected: int j;private: int k;};class A: public B{public: void display(){ cout
  • *Summary of Accessibility Keyword

  • *Accessibility after InheritanceThe stricter is adopted!The stricter is adopted!

    Accessibility in BaseInheritance Accessibility in Derivedpublicpublicpublicprotectedprotectedprivatepublicprotectedprotectedprotectedprotectedprivatepublicprivateprivateprotectedprivateprivate

  • *11.3 Constructor/Destructor in InheritanceThe constructors of a base class are not inherited

    How to initialize the data fields inherited from the base class?By calling base class constructors from the constructors of the derived classes

  • *Calling Base Class Constructors DerivedClass(parameterList): BaseClass(){ // Perform initialization } DerivedClass(parameterList): BaseClass(argumentList){ // Perform initialization } Circle::Circle(double radius, string color, bool filled) :GeometricObject(color, filled){this->radius = radius;}Ever saw before?Constructor Initializer!class Action{public: Action(int hr, int min, int sec) :time(hr, min, sec) { } private: Time time;}; Object name!Class name!

  • *No-Arg Constructor in Base ClassA constructor in a derived class must always invoke a constructor in its base class. If a base constructor is not invoked explicitly, the base classs no-arg constructor is invoked by default.

    For example,

    public Circle()

    {

    radius = 1;

    }

    is equivalent to

    public Circle(): GeometricObject()

    {

    radius = 1;

    }

    public Circle(double radius)

    {

    this->radius = radius;

    }

    is equivalent to

    public Circle(double radius)

    : GeometricObject()

    {

    this->radius = radius;

    }

  • *11.4 Multiple InheritanceType of InheritanceSingle () Multiple() Repeated()

  • *Multiple InheritanceSyntax:

    For example:class DerivedClass : acckeyword BaseClass, acckeyword BaseClass{ };class CPolygon { }; class COutput { }; class CRectangle :public CPolygon, public COutput { public: int area () { return (width * height); } };

  • *Constructor and Destructor ChainingMore than one constructor/destructor to invokeA()~A()C()~C()ME()~ME()class A: public B{ ...};

    class ME: public A, public C{ ... D d;};B()~B()D()~D()Invoking order of constructors: B, A, C, D, MEInvoking order of destructors: in reverse orderChainingDemoRun

  • *11.5 Redefining FunctionsA function of the base class may be redefined(in the derived classFor example:string GeometricObject::toString() { return "Geometric object color " + color + " filled " + ((filled) ? "true" : "false"); } string Circle::toString() { return "Geometric object color " + color + " filled " + ((filled) ? "true" : "false+ radius + radius); }

  • *Redefining vs. Overloading

    Overloading()Redefining()SimilarityMore than one functionThe same nameDifferenceDifferent signature (parameter list)Maybe different type (return type)The same signatureThe same typeTo provide various choicesTo shield/hide the original function

  • *Invoking Functions RedefinedTo invoke the function defined in the derived class: circle1.toString();To invoke the function defined in the base class:circle1.GeometricObject::toString();Scope resolution operator()

  • *11.6 Virtual Function and PolymorphismWhat we want?class HM {public: void show(){ coutshow(); delete hm;}HumanHumanHumanHumanChineseCantonesePolymorphism()

  • *PolymorphismListing 11.9 to demonstrate polymorphism

    Polymorphism()Also called dynamic binding ()Two elementsVirtual function ()Pointer of base classRunWhyPolymorphismDemoRunPolymorphismDemo

  • *Virtual FunctionsThe function declared with the keyword virtual

    OverridingTo redefine a virtual function in the derived classclass C { public: virtual string toString() { return "class C"; } }; class B: public C { string toString() { return "class B"; } };

  • *NoteIf a function is defined virtual in a base class, it is automatically virtual in all its derived classesIt is not necessary to add the keyword virtual in the function declaration in the derived class

  • *Pointer of Base Classvoid displayObject(C *p) { cout toString().data()
  • *Matching vs. BindingMatching ()To match the function call with the function signatureAt compiling timeBinding ()To bind the function call with the function implementationTwo types of bindingStatic binding(,early binding)At compiling timeDynamic binding(, late binding) polymorphismAt runtime

  • *11.7 Abstract ClassesClass is the abstraction of instances/objectsA base class is more abstract/general than derived classesAbstract class ()In logic: A class so abstract that it cannot have any specific instancesIt can only be used as base class In syntax:A class with abstract functions ()For example, GeometricObject

  • *Abstract FunctionI.e. Pure Virtual Function ()Cant be implemented in abstract classesFor exampleclass GeometricObject{protected: GeometricObject(); GeometricObject(string color, bool filled);

    public: string getColor(); void setColor(string color); bool isFilled(); void setFilled(bool filled); string toString(); virtual double getArea() = 0; virtual double getPerimeter() = 0;

    private: string color; bool filled;};

    protected

    GeometricObject

    -color: string

    -filled: bool

    #GeometricObject()

    #GeometricObject(color: string, filled: bool)

    +getColor(): string

    +setColor(color: string): void

    +isFilled(): bool

    +setFilled(filled: bool): void

    +tostring(): string

    +getArea(): double

    +getPerimeter(): double

  • *Abstract Class ExampleAbstractGeometricObject.hRunAbstractGeometricObject.cppDerivedCircle2.hDerivedCircle2.cppRectangle2.hRectangle2.cppTestGeometricObject2 .cpp

    Rectangle

    -width: double

    -height: double

    +Rectangle()

    +Rectangle(width: double, height: double)

    +Rectangle(width: double, height: double, color: string, filled: bool)

    +getWidth(): double

    +setWidth(width: double): void

    +getHeight(): double

    +setHeight(height: double): void

    GeometricObject

    -color: string

    -filled: bool

    #GeometricObject()

    #GeometricObject(color: string, filled: bool)

    +getColor(): string

    +setColor(color: string): void

    +isFilled(): bool

    +setFilled(filled: bool): void

    +tostring(): string

    +getArea(): double

    +getPerimeter(): double

    Circle

    -radius: double

    +Circle()

    +Circle(radius: double)

    +Circle(radius: double, color: string, filled: bool)

    +getRadius(): double

    +setRadius(radius: double): void

    +getDiameter(): double

  • *11.8 Dynamic CastingThe display function in Listing 11.18

    How to display radius, diameter, area, and perimeter if the object is a circle?// A function for displaying a geometric objectvoid displayGeometricObject(GeometricObject &object){ cout

  • *Dynamic CastingThe dynamic_cast operator checks if p points to a Circle objectIf yes, p1 is assigned the address of the objectIf no, p1 is assigned to NULL (the constant 0)GeometricObject *p = &object;Circle *p1 = dynamic_cast(p);if (p1 != NULL){ cout
  • *Upcasting and DowncastingUpcastingAssigning a pointer of a derived class type to a pointer of its base class typeDone implicitly

    DowncastingAssigning a pointer of a base class type to a pointer of its derived class typeDone explicitly using dynamic_cast

    GeometricObject *p = new Circle(1);Circle *p1 = new Circle(2);p = p1;p1 = dynamic_cast(p);

  • *The typeid Operator To return the type information of a variable/objectThe information is stored in an object of class type_infoFor example, string x;cout
  • *A SummaryConcept of inheritanceThe protected keywordAccessibility in derived calssesMultiple Inheritance, constructor/destructor chainingVirtual function and polymorphismPure virtual functions and abstract classesThe dynamic_cast operator

  • *Homework QuestionsPoint out the errors in the following code. Assume the implementation of the classes is correct and omitted due to the limit of space. class BOX{public: BOX(int, int, int, int, char*, int); ~BOX(); int show(); int hide(); int move(int, int); int zoom(int);protected: int draw(); int start_x, start_y; int width, height; char *title; int color;};class DialogBox: BOX{public: DialogBox(int, int, int, int, char*, int, char*, char*); ~DialogBox(); int select();private: int draw(); char *ok_button; char *cancel_button;};//. The Implementation of the classes is omitted.// int main(){ DialogBox dlg(0, 0, 15, 13, "test", 1, "OK", "Cancel"); dlg.move(19, 20);}

  • *Homework Questions (cont)Write down the output of the following code.class Base1{public: Base1( int x ){ cout
  • *Homework Questions (cont)Describe the difference between virtual function and abstract function.How is the polymorphism enabled?What is the difference between dynamic casting and static casting?